Make Illegal States Unrepresentable
Medium About 35 min Free, no account needed
One mutable Parcel carries a status string plus fields that are null in most stages, and every desk operation guards the status at runtime. Model each stage as its own immutable type that carries only its data, refuses to exist without it, and offers only its legal moves, so an illegal move stops compiling.
The brief
Shipping.Parcel follows a parcel from pickup to its final stage. A parcel is pending, then shipped
with a tracking number, then either delivered (someone signed for it) or returned (with a reason).
The behavior is right, but the model is one mutable class for every stage:
Statusis a settable string, so any caller can writeparcel.Status = "delivered".TrackingNumber,SignedBy, andReturnReasonexist on every parcel and are null in most stages. A pending parcel with aSignedByis a perfectly valid object.ParcelDesk.Deliver(pendingParcel, "Ana")compiles. Only a runtime status check stops it, andDescribetrusts that the right fields were filled for each status.
Every rule about which data exists in which stage, and which move is legal from which stage, lives in guards and conventions the compiler cannot see. The fix is to let the types say it: one type per stage, carrying exactly the data that stage has, offering exactly the moves that stage allows. Then an illegal move does not compile, and an illegal state cannot be constructed.
Scanner events arrive as ship:<tracking number>, deliver:<signed by>, and return:<reason>, each
with a non-empty value. Preserve every reply (shipped:<tracking>, delivered:<tracking>:<signed by>,
returned:<tracking>:<reason>, and rejected:<verb>:<current status> for a move the current stage
does not allow) and the final description.
Make Parcel an abstract, immutable base that holds only what every stage has: Id, a get-only
Status, and string Describe(). Model each stage as its own sealed, immutable type, with exactly
its own data and its own moves:
- A new parcel is
new PendingParcel(id).Ship(trackingNumber)returns aShippedParcel. - A
ShippedParcelhas aTrackingNumber.Deliver(signedBy)returns aDeliveredParcel, andReturn(reason)returns aReturnedParcel. - A
DeliveredParcelhasTrackingNumberandSignedBy, aReturnedParcelhasTrackingNumberandReason, and neither offers another move.
A move returns a new stage and leaves the old one untouched. Status reads pending, shipped,
delivered, or returned. A stage also cannot exist without its data: an id, tracking number,
signer, or reason that is null, empty, or only whitespace is refused with an exception, whichever way
the stage is being built. Beyond new PendingParcel(id) and the moves, how the stages come into
existence is your call. Remove ParcelDesk.
The scanner feed is untyped text. "deliver:Ana" arrives with no type the compiler could hold
against the parcel's stage, so Solution is the one place that still decides at runtime which move
the current stage allows. A switch over the stage and the verb, with a default arm that replies
rejected:<verb>:<status>, is the right tool at that boundary: the default is the real answer for
input that names a move the stage does not have. Past that boundary, every call is made on a type
that only offers legal moves. Code that already holds typed values is a different case, and a
default arm there tends to hide a missing case instead of answering one.
This is the opposite trade-off from the kata transition-through-state-objects, where every state
answers every action through one uniform Step and ignores the illegal ones at runtime. That shape
fits when all input is untyped and every state must respond. Typestate fits when callers hold typed
values and an illegal move should never get past the compiler.
Your submission must (1) preserve every reply and final description, including rejected moves
and moves after a final stage, and (2) satisfy every design rule shown in the results: Parcel
is abstract and immutable, all four stages exist and are sealed and immutable, pending leads to
shipped, and shipped leads to delivered and returned.
A trusted caller then lists the public moves and data of each stage type, inherited members and the
members of the interfaces it implements included, and walks the lifecycle through typed calls. Only
PendingParcel may offer Ship, only ShippedParcel may offer Deliver and Return, a pending
parcel has no TrackingNumber, and only the final stages carry SignedBy and Reason. It also
ships the same pending parcel twice and expects it to still be pending. Last, it tries to build each
stage with a missing id, tracking number, signer, or reason, through new PendingParcel(id), through
the moves, through every public constructor of every stage, through every public static method that
returns a stage, and through every public init accessor, which is what a with expression calls.
It expects each attempt to throw.
If a combination of values should never happen, do not write a guard for it. Pick types in which it cannot be written down.
How it is graded
Executable structural checks grade the shape of your types as well as their behavior.
What it practices
- Illegal states unrepresentable
- Model each state as its own type so invalid combinations cannot be constructed.
Related katas
- History Keeps a Checkpoint, Not Editor Internals Medium Free Capture immutable mementos that can be restored repeatedly while the history caretaker stays unaware of the editor’s stored representation.
- Four Layers for One Formula Medium Free A report-card service reaches its one weighted formula through a factory, a calculator contract, a base class, and a selector, each added so it could be swapped one day. Take out every layer nothing varies behind and keep the one abstraction that really varies, without changing a single report card.
- Freeze the Money Medium Free Money pretends to be a value object: its arithmetic returns new instances, but its Amount and Currency are still publicly settable over a mutable field. Make it structurally immutable, and don't let the reflex
private setfool you; it hides the setter but leaves the backing field writable. - An OrderId Is Not a CustomerId Medium Free OrderBook and its three callers identify orders and customers with bare ints, so a swapped argument compiles and quietly files an order under the wrong customer. Give each identifier its own value type that only ever holds a positive number, and bring the callers along without reopening the hole.