Skip to main content
InterviewHubPRO
Section Overview
Q19

Question 19 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

38%
Domain-Driven Design (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

How do Factories work in Domain-Driven Design?

senior LevelCode ExampleSystem Design

In Simple Words: When creating an Aggregate Root requires complex validation, default invariants, or assembly of nested value objects:

  • Encapsulate the creation logic inside a dedicated Factory (method or class):
  • Guarantees that an entity can never exist in an invalid, half-initialized state:
typescript
class OrderFactory {
  static createNewOrder(customerId: CustomerId, items: CartItem[]): Order {
    if (items.length === 0) throw new DomainException("Order must have items");
    const orderItems = items.map(i => new OrderItem(i.sku, i.quantity, i.price));
    return new Order(OrderId.generate(), customerId, orderItems, OrderStatus.Pending);
  }
}