💻 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."