0Pricing
Clean Architecture & Design Patterns in Practice · レッスン

不変条件によるビジネスルールの強制

重要なビジネスルールをエンティティ内の不変条件として定義し、ドメインが無効な状態に入らないようにする方法を学びます。

「不変条件によるビジネスルールの強制」はCoddyKit上の無料Clean Architecture & Design Patterns in Practiceレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはClean Architecture & Design Patterns in Practice学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Clean Architecture & Design Patterns in Practiceコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Rules That Must Always Hold

Beyond use-case logic, a domain has rules that must be true at all times. An account balance never goes below zero; an order always has at least one line item.

These are invariants, and the core should make them impossible to violate.

Entity Invariants vs Use-Case Rules

Two layers of rules exist:

  • Entity invariants: always true regardless of operation (Enterprise Business Rules).
  • Use-case rules: govern a specific workflow (Application Business Rules).

Invariants belong inside the entity itself.

The Danger of Anemic Entities

An anemic entity is just public fields with no protection.

class Account {
    public double balance; // anyone can set anything
}

Guarding Construction

Enforce invariants when the entity is created. An invalid entity should never exist.

class Account {
    private double balance;
    Account(double initial) {
        if (initial < 0) throw new IllegalArgumentException("balance < 0");
        this.balance = initial;
    }
}

Guarding Mutation

Every state change must preserve the invariant. Expose intent-revealing methods, not setters.

void withdraw(double amount) {
    if (amount <= 0) throw new IllegalArgumentException("amount");
    if (amount > balance) throw new IllegalStateException("insufficient funds");
    balance -= amount;
}

Make Illegal States Unrepresentable

A stronger goal than checking: design types so invalid states cannot be expressed.

Use value objects, enums, and required constructor arguments so the compiler enforces what it can before runtime checks ever run.

Value Objects Carry Their Own Rules

Wrap primitives in small immutable types that validate themselves.

final class Email {
    private final String value;
    Email(String v) {
        if (!v.contains("@")) throw new IllegalArgumentException("bad email");
        this.value = v;
    }
}

A Runnable Demonstration

The entity rejects an invalid operation, protecting the invariant.

public class Main {
  static class Account {
    private double balance;
    Account(double b){ if(b<0) throw new IllegalArgumentException(); balance=b; }
    void withdraw(double a){ if(a>balance) throw new IllegalStateException("insufficient"); balance-=a; }
    double getBalance(){ return balance; }
  }
  public static void main(String[] args){
    Account acc = new Account(100);
    acc.withdraw(30);
    System.out.println("Balance: " + acc.getBalance());
    try { acc.withdraw(1000); } catch(Exception e){ System.out.println("Blocked: " + e.getMessage()); }
  }
}

Keep Infrastructure Out

Invariant checks are pure domain logic. They must not reach for a database, network, or framework.

If validating a rule needs external data, that check belongs in a use case (interactor), not the entity.

Invariants and Testing

Because invariants live in pure entities, they are trivial to test: construct, call a method, assert the rule held or the operation was rejected.

No mocks, no database, no framework — fast and reliable tests.

Design Guidelines

  • Validate on construction and on every mutation.
  • Replace public setters with intent-revealing methods.
  • Use immutable value objects for self-validating data.
  • Keep all checks framework-free.

Quick Check

Test your understanding of invariants.

Recap

You learned to protect the domain with invariants.

  • Entity invariants always hold; use-case rules govern workflows.
  • Validate on creation and mutation; prefer unrepresentable illegal states.
  • Keep checks pure for easy testing.

よくある質問

「不変条件によるビジネスルールの強制」レッスンは無料ですか?

はい。「不変条件によるビジネスルールの強制」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Clean Architecture & Design Patterns in Practiceコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Clean Architecture & Design Patterns in Practiceコースには全4レッスンが含まれています。

「不変条件によるビジネスルールの強制」で何を学びますか?

重要なビジネスルールをエンティティ内の不変条件として定義し、ドメインが無効な状態に入らないようにする方法を学びます。 ブラウザで直接実行するハンズオンコードでClean Architecture & Design Patterns in Practiceを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Clean Architecture & Design Patterns in Practiceを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのClean Architecture & Design Patterns in Practiceは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「不変条件によるビジネスルールの強制」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このClean Architecture & Design Patterns in Practiceレッスンでコードを書いて実行できますか?

はい。すべてのClean Architecture & Design Patterns in Practiceレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ビジネスエンティティの設計
  2. Use Cases(Interactors)の実装
  3. InputとOutputのPorts
  4. 不変条件によるビジネスルールの強制
← Clean Architecture & Design Patterns in Practiceに戻る