0Pricing
Clean Architecture & Design Patterns in Practice · 课时

使用不变量强制执行业务规则

学习如何将关键业务规则编码为实体内部的不变量,确保领域永远不会进入无效状态。

使用不变量强制执行业务规则 是 CoddyKit 上的免费 Clean Architecture & Design Patterns in Practice 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

常见问题解答

「使用不变量强制执行业务规则」课时是免费的吗?

是的 — 「使用不变量强制执行业务规则」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clean Architecture & Design Patterns in Practice 课程的其余内容,请升级到 CoddyKit PRO。 Clean Architecture & Design Patterns in Practice 课程共包含 4 节课。

「使用不变量强制执行业务规则」这节课中我会学到什么?

学习如何将关键业务规则编码为实体内部的不变量,确保领域永远不会进入无效状态。 你通过在浏览器中直接运行的动手代码来练习 Clean Architecture & Design Patterns in Practice,全天候 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. 实现用例(交互器)
  3. 输入与输出端口
  4. 使用不变量强制执行业务规则
← 返回 Clean Architecture & Design Patterns in Practice