Egzekwowanie reguł biznesowych za pomocą niezmienników
Nauczą się Państwo zapisywać kluczowe reguły biznesowe jako niezmienniki wewnątrz encji, aby domena nigdy nie mogła znaleźć się w nieprawidłowym stanie.
Egzekwowanie reguł biznesowych za pomocą niezmienników to bezpłatna lekcja Clean Architecture & Design Patterns in Practice na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Clean Architecture & Design Patterns in Practice, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Clean Architecture & Design Patterns in Practice zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Ucz się Clean Architecture & Design Patterns in Practice dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 12
- Lekcje
- 48
Często zadawane pytania
Czy lekcja „Egzekwowanie reguł biznesowych za pomocą niezmienników” jest bezpłatna?
Tak — pełny tekst „Egzekwowanie reguł biznesowych za pomocą niezmienników” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Clean Architecture & Design Patterns in Practice, przejdź na CoddyKit PRO. Kurs Clean Architecture & Design Patterns in Practice zawiera 4 lekcji w sumie.
Co nauczysz się w „Egzekwowanie reguł biznesowych za pomocą niezmienników”?
Nauczą się Państwo zapisywać kluczowe reguły biznesowe jako niezmienniki wewnątrz encji, aby domena nigdy nie mogła znaleźć się w nieprawidłowym stanie. Ćwiczysz Clean Architecture & Design Patterns in Practice z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Clean Architecture & Design Patterns in Practice?
Nie wymagamy żadnego doświadczenia. Clean Architecture & Design Patterns in Practice w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Egzekwowanie reguł biznesowych za pomocą niezmienników”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Clean Architecture & Design Patterns in Practice?
Tak. Każda lekcja Clean Architecture & Design Patterns in Practice zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Projektowanie encji biznesowych
- Implementowanie Use Cases (Interactorów)
- Porty wejścia i wyjścia
- Egzekwowanie reguł biznesowych za pomocą niezmienników