Domain modeling and invariants
What you will learn
Domain-driven design starts with the rules and vocabulary of the business. A value object describes a value, an entity has continuing identity, and an aggregate root is responsible for rules that must hold across a group of objects. These boundaries are design decisions, not ORM annotations.
- Create immutable values with explicit validation.
- Enforce reservation invariants through an aggregate root.
- Distinguish domain events from durable delivery and separate bounded contexts.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. All examples in this chapter are standalone, single-threaded Java 21 models unless stated otherwise.
Validated value objects
public class Main { record Sku(String value) { Sku { value = java.util.Objects.requireNonNull(value).strip() .toUpperCase(java.util.Locale.ROOT); if (!value.matches("[A-Z0-9-]{1,20}")) throw new IllegalArgumentException("SKU"); } } public static void main(String[] args) { var a = new Sku(" pen "); var b = new Sku("PEN"); System.out.println(a.equals(b)); try { new Sku(" "); throw new AssertionError(); } catch (IllegalArgumentException expected) { System.out.println("invalid SKU"); } }}Expected output:
trueinvalid SKUThe fictional domain defines an uppercase ASCII SKU after normalization. The record stores the normalized value and supplies value equality; an actual organization may have a different identifier contract.
Vocabulary and bounded contexts
Use terms agreed with domain experts. In a sales context, an item may be a product offer; in warehousing, the same SKU may identify a stock position. A bounded context describes where a model has a coherent meaning. Contexts can live in the same process; they do not require microservices. Translate explicit contracts at their boundary rather than sharing every internal entity.
Aggregate consistency and ownership
An invariant is a rule that must hold whenever a valid state is observed, such as reserved quantity never exceeding capacity. The root exposes operations that protect those rules. A value object compares by its values and should not expose mutable internals. A repository loads and saves aggregates; persistence, locking, and transaction boundaries are additional concerns. Do not assume an in-memory object is safe for concurrent use or that one transaction should span every related entity.
Domain events and state changes
A domain event represents a fact after a successful change, such as ReservationAccepted. It is not a request to perform that action. Use immutable event data; publish after durable commit through an appropriate mechanism such as the transactional outbox from Chapter 46. An in-memory list is not durable and no broker delivery is demonstrated here.
Aggregate protects capacity and emits facts
public class Main { record Reserved(int quantity) {} static class Stock { private int available; private final java.util.List<Reserved> events = new java.util.ArrayList<>(); Stock(int capacity) { if (capacity < 0) throw new IllegalArgumentException("capacity"); available = capacity; } void reserve(int n) { if (n <= 0 || n > available) throw new IllegalArgumentException("quantity"); available -= n; events.add(new Reserved(n)); } int available() { return available; } java.util.List<Reserved> events() { return java.util.List.copyOf(events); } } public static void main(String[] args) { var stock = new Stock(5); stock.reserve(3); try { stock.reserve(3); throw new AssertionError(); } catch (IllegalArgumentException expected) { System.out.println("rejected"); } System.out.println(stock.available()); var events = stock.events(); System.out.println(events); try { events.clear(); throw new AssertionError(); } catch (UnsupportedOperationException expected) { System.out.println("snapshot protected"); } }}Expected output:
rejected2[Reserved[quantity=3]]snapshot protectedThe rejected action neither subtracts stock nor appends an event. The root returns a snapshot instead of exposing its list. This is a single-threaded model, not a transactional event store.
Translate a boundary contract
public class Main { record Offer(String sku, int priceCents) {} record StockPosition(String sku, int onHand) {} record Availability(String sku, boolean inStock) {} static Availability toAvailability(StockPosition position) { return new Availability(position.sku(), position.onHand() > 0); } public static void main(String[] args) { var offer = new Offer("PEN", 250); var position = new StockPosition("PEN", 4); System.out.println(toAvailability(position)); System.out.println(offer.priceCents()); }}Expected output:
Availability[sku=PEN, inStock=true]250Sales and warehouse models have different responsibilities, even with a shared SKU. The translation exposes a limited availability fact, not an authoritative reservation promise. A real boundary must handle freshness, authorization and contract evolution.
Common mistakes
A public setter can bypass an invariant. A record with a mutable component is not deeply immutable. A domain event in memory is not evidence of durable delivery. Do not turn every database row into an aggregate or every bounded context into a network service.
Practice
Implement a ticket allocation aggregate with capacity 4. Allocate 2, reject allocation of 3, then allocate 2. Return an immutable list of successful event quantities and print the remaining capacity and event list.
Expected output:
rejected0[2, 2]Compare with the manual review criteria.
Further reading: Aggregate · Bounded context. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Domain modeling and invariants — knowledge check
Design and domain modeling reasoning.
What is an aggregate root responsible for?
What does a value object compare by?
What is a bounded context?
What should happen when capacity validation fails?
Does an in-memory event list prove durable delivery?