Domain-Driven Design (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is the Repository Pattern in DDD and what is its strict contract?
senior LevelCode ExampleSystem Design
In Simple Words: A Repository simulates an in-memory collection of Aggregate Roots:
- Rule 1: Only Aggregate Roots can have Repositories! You create an
OrderRepository, but you NEVER create anOrderItemRepository. - Rule 2: The repository interface lives in the Domain Layer, but its implementation lives in the Infrastructure Layer (DIP):
typescript
// Domain Layer:
interface OrderRepository {
findById(id: OrderId): Promise<Order | null>;
save(order: Order): Promise<void>;
}