Lesson 2 of 9 · 26m
Sealed Types Make Illegal States Compile-Time Errors
Replace stringly typed status fields and visitor boilerplate with sealed hierarchies the compiler can exhaustively check.
Most production outages caused by domain modeling are not exotic. They are states nobody expected: an order that is both cancelled and shipped, a payment with no failure reason, a user whose role string is amdin. Sealed types attack that class of mistake. They let you say exactly which shapes exist and force the compiler to participate when a new one arrives.
Model alternatives as types
Suppose a payment can be pending, authorized, captured, or failed. The legacy version is usually a class with a status string and nullable fields whose validity depends on that string. The modern version names each alternative:
public sealed interface PaymentState
permits Pending, Authorized, Captured, Failed {}
record Pending(Instant createdAt) implements PaymentState {}
record Authorized(String authorizationCode) implements PaymentState {}
record Captured(String authorizationCode, Instant capturedAt) implements PaymentState {}
record Failed(String reason, boolean retryable) implements PaymentState {}Now Failed cannot exist without a reason, and Pending cannot accidentally grow a capture timestamp. The type system is carrying the invariant instead of a wiki page.
Exhaustiveness is the payoff
The payoff appears when consuming the hierarchy:
String describe(PaymentState state) {
return switch (state) {
case Pending p -> "created at " + p.createdAt();
case Authorized a -> "authorized " + a.authorizationCode();
case Captured c -> "captured at " + c.capturedAt();
case Failed f when f.retryable() -> "temporary failure: " + f.reason();
case Failed f -> "permanent failure: " + f.reason();
};
}When a new state is added, the switch stops compiling until someone makes a decision. That is not friction; that is the design working. A default branch would silence the exact signal you want.
Persistence and serialization need translation
Databases still like columns and discriminators. JSON often likes a type field. Treat those as encodings, not as reasons to pollute the domain. Map storage representations into sealed domain objects at the boundary:
PaymentState decode(PaymentRow row) {
return switch (row.status()) {
case "pending" -> new Pending(row.createdAt());
case "authorized" -> new Authorized(row.authorizationCode());
case "captured" -> new Captured(row.authorizationCode(), row.capturedAt());
case "failed" -> new Failed(row.failureReason(), row.retryable());
default -> throw new IllegalArgumentException("unknown status: " + row.status());
};
}The ugly unknown row is isolated where bad data enters the system. Downstream code sees only valid states.
Field notes
- Sealed types model finite alternatives; they are not a general replacement for interfaces.
- Prefer exhaustive switches without
defaultwhen every alternative deserves explicit handling. - Put small closed hierarchies in one file when they are conceptually one abstraction.
- Sealed types do not replace validation of untrusted input; they preserve invariants after validation.
- If two states share behavior, ask whether that is an interface method, a helper, or a sign the split is wrong.
Was this lesson helpful?