Model closed domains with Java records and sealed types
8 steps · about 4 h 20 min · Intermediate
- Represent immutable data with records (guide, Java documentation, 35 min)
Records supply a compact value-oriented model with explicit components and stable equality.
- Close a hierarchy with sealed types (guide, Java documentation, 30 min)
A sealed parent states exactly which implementations belong to the domain family.
- Inspect domain values with patterns (guide, Java documentation, 35 min)
Pattern matching combines safe type checks and bindings without manual casts.
- Handle every permitted case in switch (guide, Java documentation, 30 min)
Exhaustive switching turns a closed hierarchy into compiler-checked business logic.
- Put invariants at construction boundaries (guide, Java documentation, 25 min)
Validation before an object escapes keeps invalid states out of downstream code.
- Distinguish invalid input from unexpected defects (guide, Java documentation, 30 min)
A deliberate exception contract makes construction and operation failures understandable to callers.
- Write reusable operations over the model (guide, Java documentation, 35 min)
Bounded generic helpers can preserve type information across domain transformations.
- Test every subtype and invalid boundary (guide, JUnit documentation, 40 min)
Parameterized cases prove the closed model behaves consistently across its complete state family.