Skip to the guide

Modelling a lifecycle with a state machine: orders, elevators, vending machines

IntermediatePattern7 pages

An order, a support ticket or a claim moves through a fixed set of states, and only some moves are legal. This move writes the legal moves in one table of states and events, so one class applies them and refuses everything else. It uses enums for the states and events. It is the simpler rival of State when the states do no work of their own, while elevators and vending machines have states that do, as those pages show. Interviewers listen for where a rule such as "can't cancel after shipping" lives, and for when a table is too simple.

A board game with arrows

Think of a board game whose squares are joined by arrows, each labelled with the name of a card. You stand on one square and draw a card. If an arrow with that name leaves your square, you follow it, and if none does, you stay where you are. Nobody memorises where each card is allowed, because the board shows it all. A few arrows have a small gate, which you may pass only if you hold a key, and you find out at once.

In code, your piece is this page's Claim, and its square is a ClaimState. A card is a ClaimEvent, and the board is the Lifecycle, a table of Move rows. A gate is a guard, a small check on one row.