Video in progress
How do you choose between building the domain model with a sealed interface plus records and a classic polymorphic hierarchy?
Sealed + records are good when the set of types is closed and operations are many and often added: a switch gets an exhaustiveness check. Classic polymorphism fits when types keep getting added and the operations are stable. These are the two sides of the "expression problem".
📖 Answer
There are two axes: adding a new type and adding a new operation. No approach makes both cheap.
// A data-oriented approach
sealed interface Payment permits Card, Cash, Installment {}
record Card(String pan, Money amount) implements Payment {}
record Cash(Money amount) implements Payment {}
record Installment(Money total, int months) implements Payment {}
Money fee(Payment p) {
return switch (p) {
case Card c -> c.amount().percent(1.5);
case Cash c -> Money.ZERO;
case Installment i -> i.total().percent(3);
}; // no default: if a new type is added, the compiler points to this spot
}
A new operation (fee, riskScore, toReceipt) is one new method, and the types don't change. A new type (Crypto) makes all the switches fail to compile, which is useful, but you have to change every place.
In a classic hierarchy (abstract class Payment { abstract Money fee(); }) it's the opposite: a new type is one class, and a new operation is a method in every class.
How I choose:
- The types are closed and rarely change in the business (payment state, a command result, an AST, event types inside one service): sealed + records. The operations can be written in different modules (accounting, reporting, audit), and the domain class isn't tied to them.
- The types multiply like plugins (payment providers, every team adds its own integration): an interface plus polymorphism, and in Spring a list of beans.
- The behavior is tightly bound to the state (an aggregate protects its own invariants): a rich object, not a record.
Watch out at team boundaries: a sealed hierarchy is closed to other modules, so they can't add a new type. That's a good guarantee for a library, but a trap for an "extensible platform".
One more practical point: don't "protect" an exhaustive switch with a default, because that switches off exactly the help the compiler gives you.
Sign up to mark studied questions and save your progress.