This guide is not dependent on a specific programming language and explains principles applicable to any language. Code examples are shown in TypeScript, but the concepts can be applied to other languages as well.
In domain-driven design, it is important to use the appropriate domain model building blocks.
Utilizing Value Objects
A value object is an object with the following characteristics:
- Has no identifier: Identity is determined solely by attributes
- Immutable: Cannot be changed once created
- Self-contained: Does not hold references to other entities
import * as E from 'fp-ts/Either';
class IllegalArgumentError extends Error { constructor(message: string) { super(message); this.name = 'IllegalArgumentError'; } }
class ValidationError { private constructor(private readonly _message: string) {}
static of(message: string): ValidationError { return new ValidationError(message); }
get message(): string { return this._message; } }
class MoneyAddError extends Error { constructor(message: string) { super(message); this.name = 'MoneyAddError'; } }
class MoneySubtractError extends Error { constructor(message: string) { super(message); this.name = 'MoneySubtractError'; } }
class AssertionError extends Error { constructor(message: string) { super(message); this.name = 'AssertionError'; } }
type MoneyProps = { amount: number; currency: string; };
class Money {
private constructor( private readonly _amount: number, private readonly _currency: string ) { if (this._amount < 0) { throw new IllegalArgumentError("The amount must be 0 or greater"); } if (!["JPY", "USD", "EUR"].includes(this._currency)) { throw new IllegalArgumentError("Unsupported currency"); } }
static of(props: MoneyProps): Money { return new Money(props.amount, props.currency); }
static validate(props: MoneyProps): E.Either<ValidationError, Money> { try { return E.right(Money.of(props)); } catch (e: unknown) { if (e instanceof IllegalArgumentError) { return E.left(ValidationError.of(e.message)); } throw new AssertionError("An unknown error occurred"); } }
private copy(props: Partial): Money { return Money.of({ amount: props.amount ?? this._amount, currency: props.currency ?? this._currency }); }
add(other: Money): E.Either<MoneyAddError, Money> { if (this._currency !== other._currency) { return E.left(new MoneyAddError("Amounts in different currencies cannot be added")); } return E.right(this.copy({ amount: this._amount + other._amount })); }
subtract(other: Money): E.Either<MoneySubtractError, Money> { if (this._currency !== other._currency) { return E.left(new MoneySubtractError("Amounts in different currencies cannot be subtracted")); } if ((this._amount - other._amount) < 0) { return E.left(new MoneySubtractError("Cannot subtract because the amount would become negative")); } return E.right(this.copy({ amount: this._amount - other._amount })); }
get breachEncapsulationOfAmount(): number { return this._amount; }
get breachEncapsulationOfCurrency(): string { return this._currency; }
equals(other: Money): boolean { return this._amount === other._amount && this._currency === other._currency; }
toString(): string {
return ${this._amount} ${this._currency};
}
}
## エンティティと集約
エンティティと集約は以下の原則に従って設計します:
1. **エンティティ**:
- 識別子を持つ
- ライフサイクルを持つ
- その状態が時間とともに変化する
2. **集約**:
- トランザクション整合性の単位
- 1つの集約ルートと複数の子エンティティや値オブジェクトから構成
- 外部からは集約ルートを通じてのみアクセス可能
```typescript
type OrderProps = {
id: OrderId;
orderItems: OrderItems;
status: OrderStatus;
};
class Order {
private constructor(
private readonly _id: OrderId,
private readonly _status: OrderStatus,
private readonly _orderItems: OrderItems
) {}
static create(props: Pick<OrderProps, "id"> & Partial<OrderProps>): Order {
return new Order(
props.id,
props.status ?? OrderStatus.DRAFT,
props.orderItems ?? OrderItems.empty()
);
}
addOrderItem(props: { product: ProductId; quantity: Quantity; unitPrice: Money }): E.Either<AddOrderItemError, Order> {
if (this._status !== OrderStatus.DRAFT) {
return E.left(new AddOrderItemError("注文確定後は商品を追加できません"));
}
const orderItem = OrderItem.create(props.product, props.quantity, props.unitPrice);
const newOrderItems = this._orderItems.add(orderItem);
return E.right(this.copy({ orderItems: newOrderItems }));
}
confirm(): E.Either<OrderConfirmationError, Order> {
if (this._orderItems.isEmpty()) {
return E.left(new OrderConfirmationError("注文に商品が含まれていません"));
}
if (this._status !== OrderStatus.DRAFT) {
return E.left(new OrderConfirmationError("すでに確定済みの注文です"));
}
return E.right(this.copy({ status: OrderStatus.CONFIRMED }));
}
equals(other: Order): boolean {
return this._id.equals(other._id) &&
this._status === other._status &&
this._orderItems.equals(other._orderItems);
}
private copy(props: Partial<OrderProps>): Order {
return new Order(
props.id ?? this._id,
props.status ?? this._status,
props.orderItems ?? this._orderItems
);
}
sameIdentityAs(other: Order): boolean {
return this._id.equals(other._id);
}
get breachEncapsulationOfId(): OrderId {
return this._id;
}
get breachEncapsulationOfStatus(): OrderStatus {
return this._status;
}
get breachEncapsulationOfOrderItems(): OrderItems {
return this._orderItems;
}
}
Domain Services
Operations that span multiple entities or value objects are implemented as domain services:
// エンティティ例: 口座(入出金はエンティティの責務)
class BankAccount {
private constructor(
private readonly _id: BankAccountId,
private readonly _balance: Money
) {}
deposit(amount: Money): E.Either<BankAccountDepositError, BankAccount> {
const result = this._balance.add(amount);
if (E.isLeft(result)) {
return E.left(new BankAccountDepositError(result.left.message));
}
return E.right(this.copy({ balance: result.right }));
}
withdraw(amount: Money): E.Either<BankAccountWithdrawalError, BankAccount> {
const result = this._balance.subtract(amount);
if (E.isLeft(result)) {
return E.left(new BankAccountWithdrawalError(result.left.message));
}
return E.right(this.copy({ balance: result.right }));
}
private copy(props: { balance?: Money }): BankAccount {
return new BankAccount(
this._id,
props.balance ?? this._balance
);
}
}
// ドメインサービスの例
// クラス名やメソッド名はユビキタス言語に対応すること
class BankAccountTransfer {
static transfer(
from: BankAccount,
to: BankAccount,
amount: Money
): E.Either<BankAccountTransferError, [BankAccount, BankAccount]> {
const newFromResult = from.withdraw(amount);
if (E.isLeft(newFromResult)) {
return E.left(new BankAccountTransferError(
`残高不足または出金元口座でのエラー: ${newFromResult.left.message}`
));
}
const newToResult = to.deposit(amount);
if (E.isLeft(newToResult)) {
return E.left(new BankAccountTransferError(
`入金先口座でのエラー: ${newToResult.left.message}`
));
}
return E.right([newFromResult.right, newToResult.right]);
}
}
// グローバル関数として定義してもよい
function bankAccountTransfer(
from: BankAccount,
to: BankAccount,
amount: Money
): E.Either<BankAccountTransferError, [BankAccount, BankAccount]> {
const newFromResult = from.withdraw(amount);
if (E.isLeft(newFromResult)) {
return E.left(new BankAccountTransferError(
`残高不足または出金元口座でのエラー: ${newFromResult.left.message}`
));
}
const newToResult = to.deposit(amount);
if (E.isLeft(newToResult)) {
return E.left(new BankAccountTransferError(
`入金先口座でのエラー: ${newToResult.left.message}`
));
}
return E.right([newFromResult.right, newToResult.right]);
}
Related skills (recommended for concurrent reading)
When using this skill, also refer to the following skills:
aggregate-design: Design rules for aggregates that bundle building blocksdomain-model-first: Development procedure for implementing building blocks test-firstparse-dont-validate: Patterns for designing value objects at the type leveldomain-primitives-and-always-valid: Design of domain primitives and smart constructors