Geschäftsregeln mit Invarianten durchsetzen
Lernen Sie, wichtige Geschäftsregeln als Invarianten in Entitäten zu codieren, damit die Domäne niemals einen ungültigen Zustand annehmen kann.
Geschäftsregeln mit Invarianten durchsetzen ist eine kostenlose Clean Architecture & Design Patterns in Practice-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Clean Architecture & Design Patterns in Practice-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Clean Architecture & Design Patterns in Practice-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Lerne Clean Architecture & Design Patterns in Practice mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „Geschäftsregeln mit Invarianten durchsetzen“ kostenlos?
Ja — der vollständige Text von „Geschäftsregeln mit Invarianten durchsetzen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Clean Architecture & Design Patterns in Practice-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Clean Architecture & Design Patterns in Practice-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Geschäftsregeln mit Invarianten durchsetzen“?
Lernen Sie, wichtige Geschäftsregeln als Invarianten in Entitäten zu codieren, damit die Domäne niemals einen ungültigen Zustand annehmen kann. Du übst Clean Architecture & Design Patterns in Practice mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Clean Architecture & Design Patterns in Practice zu starten?
Keine Vorkenntnisse erforderlich. Clean Architecture & Design Patterns in Practice auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Geschäftsregeln mit Invarianten durchsetzen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Clean Architecture & Design Patterns in Practice-Lektion Code schreiben und ausführen?
Ja. Jede Clean Architecture & Design Patterns in Practice-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Geschäftsentitäten entwerfen
- Use Cases (Interactors) implementieren
- Input- und Output-Ports
- Geschäftsregeln mit Invarianten durchsetzen