Video in progress
When is it right to split one big `Order` class into separate types by lifecycle stage (`DraftOrder`, `PlacedOrder`, `ShippedOrder`)?
When the fields present and the actions allowed differ sharply at each stage. Then the compiler stops an action in the wrong state: DraftOrder simply has no ship() method. The cost: working with several types in persistence and the API gets harder.
📖 Answer
With the single-class approach, everything is nullable and relies on runtime checks:
class Order {
Status status;
Instant placedAt; // null in DRAFT
String trackingNumber; // null until SHIPPED
void ship(String tracking) {
if (status != PAID) throw new IllegalStateException();
...
}
}
"Which field is filled in which state" lives only in the developer's head. order.getTrackingNumber().toUpperCase() throws an NPE and the compiler says nothing.
The type-state approach:
sealed interface Order permits DraftOrder, PlacedOrder, ShippedOrder {}
record DraftOrder(OrderId id, List<Line> lines) implements Order {
PlacedOrder place(Clock clock) {
if (lines.isEmpty()) throw new EmptyOrderException(id);
return new PlacedOrder(id, List.copyOf(lines), clock.instant());
}
}
record PlacedOrder(OrderId id, List<Line> lines, Instant placedAt) implements Order {
ShippedOrder ship(TrackingNumber t) { return new ShippedOrder(id, lines, placedAt, t); }
}
record ShippedOrder(OrderId id, List<Line> lines, Instant placedAt, TrackingNumber tracking)
implements Order {}
ShippedOrder.tracking() is never null. DraftOrder.ship() is a compile error.
When it's worth it:
- there are 3–5 stages and each one brings new mandatory data;
- an action in the wrong state is expensive (money, shipping goods);
- the flow is mostly one-directional.
When it isn't:
- there are many states and transitions go in every direction (payment retry, partial refund): the number of types explodes;
- with JPA: mapping one table to several immutable types is awkward. I usually keep one entity for persistence and convert to the type-state types in the domain layer, or I only use them at the API/workflow boundary.
In practice a middle path is often enough: one aggregate, but the state-dependent data sits in separate value objects (Optional<Shipment> shipment), and the actions are protected by a state machine.
Sign up to mark studied questions and save your progress.