りゅうじの学習blog

学習したことをアウトプットしていきます。

6/6 ドメイン駆動設計Chapter13 13-2

13-2 仕様とリポジトリを組み合わせる

  • リポジトリの検索のメソッド、検索の処理の中には重要なルールを含むものがある
    • 重要なルールを仕様オブジェクトに記述し、リポジトリに引き渡すようにする

プレミアムユーザであることを表す仕様オブジェクト

export class PremiumUserSpecification {
  isSatisfiedBy(user: User): boolean {
    return user.getIsPremium();
  }
}

UserエンティティにisPremiumメソッドが定義されているとする

export class User {
  constructor(
    private id: UserId,
    private name: UserName,
    private isPremium: boolean, // プレミアムユーザーかどうかを表すプロパティ
  ) {}

  // ...

  getIsPremium(): boolean { // プレミアムユーザーかどうかを返すメソッド
    return this.isPremium;
  }
}

仕様オブジェクトを使用してリポジトリからエンティティを検索するメソッドを定義

export class UserRepository {
  // ...

  findSatisfying(spec: PremiumUserSpecification): User[] {
    return this.users.filter(user => spec.isSatisfiedBy(user));
  }
}

リポジトリのメソッドを使用してプレミアムユーザーを検索するサービスを定義

export class UserApplicationService {
  constructor(private userRepository: UserRepository) {}

  findPremiumUsers(): User[] {
    const spec = new PremiumUserSpecification();
    return this.userRepository.findSatisfying(spec);
  }
}

参考

ドメイン駆動設計入門 ボトムアップでわかる!ドメイン駆動設計の基本