0Pricing
Clean Architecture & Design Patterns in Practice · Lezione

Applicare le regole di business con gli invarianti

Impari a codificare le regole di business fondamentali come invarianti all'interno delle entità, così che il dominio non possa mai trovarsi in uno stato non valido.

Applicare le regole di business con gli invarianti è una lezione Clean Architecture & Design Patterns in Practice gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Clean Architecture & Design Patterns in Practice, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Applicare le regole di business con gli invarianti» è gratuita?

Sì — il testo completo di «Applicare le regole di business con gli invarianti» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Clean Architecture & Design Patterns in Practice, passa a CoddyKit PRO. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.

Cosa imparerò in «Applicare le regole di business con gli invarianti»?

Impari a codificare le regole di business fondamentali come invarianti all'interno delle entità, così che il dominio non possa mai trovarsi in uno stato non valido. Eserciti Clean Architecture & Design Patterns in Practice con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Clean Architecture & Design Patterns in Practice?

Non è richiesta alcuna esperienza precedente. Clean Architecture & Design Patterns in Practice su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Applicare le regole di business con gli invarianti»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Clean Architecture & Design Patterns in Practice?

Sì. Ogni lezione Clean Architecture & Design Patterns in Practice include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Progettare le entità di business
  2. Implementare gli Use Cases (Interactors)
  3. Porte di input e output
  4. Applicare le regole di business con gli invarianti
← Torna a Clean Architecture & Design Patterns in Practice