🏗️ Architecture

DDD

Domain-Driven Design

DDD (Domain-Driven Design) is a methodology that places the complex business domain at the center of software design. Proposed by Eric Evans, this approach improves communication between domain experts and developers through concepts such as Ubiquitous Language, Bounded Context, and Aggregate.

📖 Detailed Explanation

Domain-Driven Design (DDD) is a software design methodology introduced by Eric Evans in 2003 in his book "Domain-Driven Design: Tackling Complexity in the Heart of Software." Its core philosophy is "The complexity of software comes from the domain, not from technology."

Strategic Design

Ubiquitous Language

A common language shared by the development team and domain experts. The same terms are used in code, documents, and conversations alike

Bounded Context

The boundary within which the same term can have different meanings. "Product" is a different model in shopping and in inventory management

Context Map

Visualizes the relationships among multiple Bounded Contexts. Defines how teams collaborate and integrate

Subdomain

Classifies business areas into Core, Supporting, and Generic subdomains

Tactical Design

Entity

An object distinguished by a unique identifier (ID). It is recognized as the same object even if its state changes during its lifecycle

Value Object

An immutable object distinguished only by its values, without an identifier. Money, Address, Email, etc.

Aggregate

A cluster of entities/value objects that forms a consistency boundary. Accessible only through the Aggregate Root

Repository

Manages the persistence of Aggregates. Abstracts storage behind a collection-like interface

Domain Service

Domain logic that does not belong to a specific entity. Business rules in which multiple Aggregates collaborate

Domain Event

Represents a significant occurrence in the domain. Loose coupling between Bounded Contexts

💻 Code Example

Value Object Implementation

// domain/value-objects/Money.ts
export class Money {
  private constructor(
    private readonly _amount: number,
    private readonly _currency: string
  ) {
    if (_amount < 0) {
      throw new Error('Amount cannot be negative');
    }
  }

  static of(amount: number, currency: string): Money {
    return new Money(amount, currency);
  }

  static zero(currency: string): Money {
    return new Money(0, currency);
  }

  get amount(): number { return this._amount; }
  get currency(): string { return this._currency; }

  add(other: Money): Money {
    this.ensureSameCurrency(other);
    return new Money(this._amount + other._amount, this._currency);
  }

  subtract(other: Money): Money {
    this.ensureSameCurrency(other);
    return new Money(this._amount - other._amount, this._currency);
  }

  multiply(factor: number): Money {
    return new Money(this._amount * factor, this._currency);
  }

  equals(other: Money): boolean {
    return this._amount === other._amount &&
           this._currency === other._currency;
  }

  private ensureSameCurrency(other: Money): void {
    if (this._currency !== other._currency) {
      throw new Error('Currency mismatch');
    }
  }
}

Entity and Aggregate Root

// domain/aggregates/Order.ts
import { Money } from '../value-objects/Money';
import { OrderItem } from '../entities/OrderItem';
import { OrderPlaced } from '../events/OrderPlaced';

export type OrderStatus = 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';

export class Order {
  private _items: OrderItem[] = [];
  private _status: OrderStatus = 'pending';
  private _domainEvents: DomainEvent[] = [];

  private constructor(
    private readonly _id: string,
    private readonly _customerId: string,
    private _shippingAddress: Address
  ) {}

  // Factory Method
  static create(customerId: string, shippingAddress: Address): Order {
    const order = new Order(
      crypto.randomUUID(),
      customerId,
      shippingAddress
    );

    // Domain Event 발행
    order.addDomainEvent(new OrderPlaced({
      orderId: order._id,
      customerId: customerId,
      occurredAt: new Date(),
    }));

    return order;
  }

  get id(): string { return this._id; }
  get customerId(): string { return this._customerId; }
  get items(): readonly OrderItem[] { return this._items; }
  get status(): OrderStatus { return this._status; }

  // 비즈니스 규칙이 담긴 메서드
  addItem(productId: string, quantity: number, unitPrice: Money): void {
    if (this._status !== 'pending') {
      throw new Error('Cannot modify confirmed order');
    }

    const existingItem = this._items.find(item => item.productId === productId);
    if (existingItem) {
      existingItem.increaseQuantity(quantity);
    } else {
      this._items.push(OrderItem.create(productId, quantity, unitPrice));
    }
  }

  removeItem(productId: string): void {
    if (this._status !== 'pending') {
      throw new Error('Cannot modify confirmed order');
    }
    this._items = this._items.filter(item => item.productId !== productId);
  }

  // Aggregate 내부 계산
  calculateTotal(): Money {
    return this._items.reduce(
      (total, item) => total.add(item.subtotal()),
      Money.zero('KRW')
    );
  }

  confirm(): void {
    if (this._items.length === 0) {
      throw new Error('Cannot confirm empty order');
    }
    if (this._status !== 'pending') {
      throw new Error('Order is not in pending status');
    }
    this._status = 'confirmed';

    this.addDomainEvent(new OrderConfirmed({
      orderId: this._id,
      totalAmount: this.calculateTotal(),
      occurredAt: new Date(),
    }));
  }

  cancel(reason: string): void {
    if (this._status === 'shipped' || this._status === 'delivered') {
      throw new Error('Cannot cancel shipped or delivered order');
    }
    this._status = 'cancelled';
  }

  // Domain Events
  pullDomainEvents(): DomainEvent[] {
    const events = [...this._domainEvents];
    this._domainEvents = [];
    return events;
  }

  private addDomainEvent(event: DomainEvent): void {
    this._domainEvents.push(event);
  }
}

Repository Interface

// domain/repositories/IOrderRepository.ts
import { Order } from '../aggregates/Order';

export interface IOrderRepository {
  findById(id: string): Promise<Order | null>;
  findByCustomerId(customerId: string): Promise<Order[]>;
  save(order: Order): Promise<void>;
  delete(id: string): Promise<void>;
  nextId(): string; // ID 생성 전략
}

Domain Service

// domain/services/OrderPricingService.ts
import { Order } from '../aggregates/Order';
import { Money } from '../value-objects/Money';
import { Customer } from '../aggregates/Customer';

export class OrderPricingService {
  // 여러 Aggregate를 조합하는 비즈니스 로직
  calculateFinalPrice(order: Order, customer: Customer): Money {
    const subtotal = order.calculateTotal();

    // 회원 등급별 할인
    const discount = this.calculateDiscount(subtotal, customer.tier);

    // 배송비 계산
    const shippingFee = this.calculateShippingFee(subtotal);

    return subtotal.subtract(discount).add(shippingFee);
  }

  private calculateDiscount(subtotal: Money, tier: CustomerTier): Money {
    const discountRates: Record<CustomerTier, number> = {
      bronze: 0,
      silver: 0.03,
      gold: 0.05,
      platinum: 0.1,
    };
    return subtotal.multiply(discountRates[tier]);
  }

  private calculateShippingFee(subtotal: Money): Money {
    // 5만원 이상 무료 배송
    if (subtotal.amount >= 50000) {
      return Money.zero(subtotal.currency);
    }
    return Money.of(3000, subtotal.currency);
  }
}

Application Service (Use Case)

// application/usecases/PlaceOrderUseCase.ts
import { IOrderRepository } from '../../domain/repositories/IOrderRepository';
import { IEventPublisher } from '../../domain/events/IEventPublisher';
import { Order } from '../../domain/aggregates/Order';
import { OrderPricingService } from '../../domain/services/OrderPricingService';

export class PlaceOrderUseCase {
  constructor(
    private orderRepository: IOrderRepository,
    private customerRepository: ICustomerRepository,
    private pricingService: OrderPricingService,
    private eventPublisher: IEventPublisher
  ) {}

  async execute(input: PlaceOrderInput): Promise<PlaceOrderOutput> {
    // 고객 조회
    const customer = await this.customerRepository.findById(input.customerId);
    if (!customer) {
      throw new Error('Customer not found');
    }

    // Order Aggregate 생성
    const order = Order.create(input.customerId, input.shippingAddress);

    // 상품 추가
    for (const item of input.items) {
      order.addItem(item.productId, item.quantity, item.unitPrice);
    }

    // 주문 확정
    order.confirm();

    // 최종 가격 계산 (Domain Service)
    const finalPrice = this.pricingService.calculateFinalPrice(order, customer);

    // 저장
    await this.orderRepository.save(order);

    // Domain Events 발행
    const events = order.pullDomainEvents();
    for (const event of events) {
      await this.eventPublisher.publish(event);
    }

    return {
      orderId: order.id,
      totalAmount: finalPrice.amount,
      status: order.status,
    };
  }
}

💬 Real-world conversation examples

👨‍💼 Domain Expert

"Before an order is 'confirmed', it should be possible to add or remove products, and after confirmation, changes should be impossible."

👩‍💻 Developer

"Then in the Order Aggregate, I'll express the business rule in code so that addItem and removeItem are allowed only when status is 'pending', and once confirm() is called, the state changes and modification is blocked."

👨‍💻 Junior developer

"Is it okay for Order to directly look up the Customer's tier to calculate the discount rate?"

👩‍💻 Senior developer

"If the Order Aggregate directly references the Customer Aggregate, the boundary breaks down. Handle that logic in a Domain Service. OrderPricingService receives both Aggregates and calculates the price."

👨‍💼 Architect

"'Product' in the shopping Context and 'product' in the inventory management Context have different concerns. In shopping, price, images, and description matter; in inventory, quantity, location, and receiving/shipping history matter. Let's separate them into their own Bounded Contexts and draw a Context Map."

⚠️ Cautions

Not every project needs DDD: Applying DDD to a simple CRUD application only adds excessive complexity. Focus on the Core Domain, where the business logic is complex.

Watch the Aggregate size: If an Aggregate is too large, concurrency problems and performance degradation occur. Design it with the minimum scope that requires transactional consistency.

No direct references between Aggregates: Reference other Aggregates only by ID. Direct object references break down the boundary.

Tip: DDD is more about communication than technology. Discover Bounded Contexts and Domain Events together with domain experts through Event Storming sessions.

🔗 Related Terms

📚 Learn More