Skip to content
cccskills
FreePublished on GitHub

domain-building-blocks

DDDのビルディングブロック(値オブジェクト、エンティティ、集約、ドメインサービス)の設計ガイド。ドメインモデリング、エンティティ設計、集約境界の決定、値オブジェクトの実装時に使用。

トリガー:「値オブジェクトを作りたい」「集約の設計」「ドメインサービスの書き方」 「エンティティと値オブジェクトの違い」「DDDで実装したい」等のドメインモデリング関連リクエストで起動。

The English summary is being prepared. Showing the original description.

See how to install

Files included (1)

  • SKILL.md9.9 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

ドメインモデルのビルディングブロック

このガイドは特定のプログラミング言語に依存せず、どの言語でも適用可能な原則を説明しています。コード例はTypeScriptで示していますが、概念は他の言語にも応用できます。

ドメイン駆動設計では、適切なドメインモデルのビルディングブロックを使うことが重要です。

値オブジェクトの活用

値オブジェクトは、以下の特性を持つオブジェクトです:

  • 識別子を持たない: 属性のみで同一性を判断
  • 不変: 一度作成したら変更できない
  • 自己完結的: 他のエンティティへの参照を持たない
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("金額は0以上である必要があります");
    }
    if (!["JPY", "USD", "EUR"].includes(this._currency)) {
      throw new IllegalArgumentError("サポートされていない通貨です");
    }
  }

  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("不明なエラーが発生しました");
    }
  }

  private copy(props: Partial<MoneyProps>): 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("通貨が異なる金額は加算できません"));
    }
    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("通貨が異なる金額は減算できません"));
    }
    if ((this._amount - other._amount) < 0) {
      return E.left(new MoneySubtractError("金額が負になるため減算できません"));
    }
    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つの集約ルートと複数の子エンティティや値オブジェクトから構成
    • 外部からは集約ルートを通じてのみアクセス可能
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;
  }
}

ドメインサービス

複数のエンティティや値オブジェクトにまたがる操作はドメインサービスとして実装します:

// エンティティ例: 口座(入出金はエンティティの責務)
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]);
}

関連スキル(併読推奨)

このスキルを使用する際は、以下のスキルも併せて参照すること:

  • aggregate-design: ビルディングブロックを束ねる集約の設計ルール
  • domain-model-first: テストファーストでビルディングブロックを実装する開発手順
  • parse-dont-validate: 値オブジェクトを型レベルで設計するパターン
  • domain-primitives-and-always-valid: ドメインプリミティブとスマートコンストラクタの設計

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

DDDの集約(Aggregate)設計ルールに基づくコードレビュー・設計支援・リファクタリングを行う。 Evans Rules、Vernon's 4 Rules、Design by Contractに基づき、集約の境界定義、不変条件の検証、 不変(Immutable)設計、ID参照、結果整合性、ドメインイベント連携を包括的にガイドする。 以下のいずれかに該当する場合は必ずこのスキルを使用すること: - 集約(Aggregate)の新規設計・実装・リファクタリング(どの言語でも) - 既存の集約やエンティティクラスのDDD観点でのコードレビュー - 集約の境界決定(「AとBは同じ集約にすべきか?」「この集約は大きすぎるか?」) - 集約内の不変条件・整合性境界の設計 - 集約間の連携方式の判断(ドメインイベント、結果整合性、Sagaパターン) - 可変(Mutable)な集約コードを不変(Immutable)設計にリファクタリングする - publicフィールド、直接参照、push/appendなどカプセル化違反の検出・修正 キーワード例:集約、Aggregate、aggregate boundary、集約ルート、AggregateRoot、 エンティティ設計、DDD実装、Vernon Rules、Evans Rules、集約の分割、真の不変条件

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

集約とトランザクション境界の関係を明確化し、複数集約を単一トランザクションに含めるアンチパターンを 検出・是正する。集約は強い整合性境界であり、ユースケースで複数集約を更新する場合は結果整合性を 使うべきという原則を適用する。コードレビュー、ユースケース設計、リファクタリング時に トランザクション境界の問題を検出する場合に使用。 対象言語: 言語非依存(Java, Kotlin, Scala, TypeScript, Go, Rust, Python等すべて)。 トリガー:「複数集約を同じトランザクションで更新している」「ユースケースに@Transactionalがある」 「集約間の整合性をどう取るか」「Sagaパターンを使うべきか」「トランザクション境界の設計」 「1トランザクション1集約」「結果整合性の実装」「集約をまたぐトランザクション」 といったトランザクション境界関連リクエストで起動。

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

後方互換性がゴミコードを量産する構造を検出し、互換性を「契約と撤去計画」として管理する ガバナンスを支援するスキル。公開API境界の明確化、非推奨化サイクル(deprecation cycle)の 制度化、互換層の局所化(Adapter/Strangler Fig)、契約テスト(CDC)による互換性検証、 AI生成コードの互換性ゲート設計を含む。コードレビュー、API設計、リファクタリング、 レガシー移行時に互換性起因の技術的負債を防ぐために使用。 対象言語: 言語非依存(Java, TypeScript, Go, Python, Rust等すべて)。 トリガー:「後方互換性を保ちたい」「非推奨APIをどうする」「互換層が増えてきた」 「レガシー移行の戦略」「API設計レビュー」「互換性のためのコードが多い」 「deprecation policyを作りたい」「破壊的変更の管理」といった互換性管理関連リクエストで起動。

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

getterの濫用を防ぐための命名規約スキル。ドメインモデルでgetterが必要な場合(永続化、JSON変換など)に `breachEncapsulationOf` プレフィックスを付与することで、カプセル化を破っていることを明示する。 これにより、Tell Don't Ask原則の違反を未然に防ぎ、getterの意図しない使用を抑制する。 コードレビュー、新規実装、リファクタリング時にgetter設計が必要な場合に使用。 対象言語: Java, Kotlin, Scala, TypeScript, Python, Go, Rust。 トリガー:「getterの命名規約」「カプセル化を破るgetter」「永続化用のgetter」 「breachEncapsulation」「getterを作りたいが濫用を防ぎたい」といったgetter命名関連リクエストで起動。

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

クリーンアーキテクチャを採用しているプロジェクト向けの設計・レビュー支援。4層構造(ドメイン層、 ユースケース層、インターフェースアダプタ層、インフラストラクチャ層)に基づく。特にインフラ層は 横断的関心事(ロギング、設定管理)のみ、永続化やRPCはインターフェースアダプタ層に配置すべき という原則を適用する。トリガー:「クリーンアーキテクチャで」「クリーンアーキテクチャに従って」 「クリーンアーキテクチャのレビュー」など、クリーンアーキテクチャを明示的に指定した場合のみ起動。 一般的な「設計レビュー」「アーキテクチャ相談」では起動しない。

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

CQRS/ESが集約の境界定義とモデリングに与える影響を解説する。CQRSを導入すると集約は コマンド実行に必要な最小限の状態のみ保持すればよくなり、読み取り責務はリードモデルに 委譲できる。大きすぎる集約の軽量化、集約境界の再定義、イベントによる状態管理を支援する。 集約設計、CQRS導入時のモデリング見直し、パフォーマンス問題の解決時に使用。 対象言語: 言語非依存。 トリガー:「CQRSで集約が変わる」「集約が大きすぎる」「集約にメッセージ1000件」 「集約の更新が重い」「CQRS導入で集約を見直す」「集約を軽量化したい」 「集約にクエリ用データが混ざっている」「集約の境界を再定義」 といったCQRS/モデリング関連リクエストで起動。

The English summary is being prepared. Showing the original description.

j5ik2o/okite-ai80Updated Apr 25, 2026

See all skills by j5ik2o

Report a problem with this skill