Part 4 of 6 · 1 min read
Transitions
In the states or in the context.
GoF notes a design choice: the context can decide the next state, or the state classes can. When states decide, as above, each state knows its successors. That keeps the rules next to the behaviour, and adding a state means writing one class, though that class must know the others. When the context decides, with a transition table, the rules sit in one place, and states stay simple.
For a larger machine, a table can be clearer than classes. A map from a pair of state and event to the next state shows every legal move at once and is easy to review with a product owner. State classes win when each state has real behaviour of its own, such as different prices, messages or side effects. A table wins when the only thing that differs is where to go next.
HF's gumball machine uses classes because each state does different work on each action: take a coin, turn the crank, dispense. In an interview, draw the states as boxes and the events as arrows first. Then say which design you would write.
Another option is a Java enum with constant-specific methods. EJ Item 34 shows enum constants that each supply their own implementation of an abstract method. A state machine fits this form well when the states are fixed and few, because the whole machine sits in one small enum. The limits are that an enum cannot extend a class, and all states live in one file.
Common mistake
Keeping state in a field and also in the state objects, so that the two disagree. Let one place be the truth: the current state object.
Check yourself: 1. What is a benefit of letting the states decide their successors? 2. When is a transition table the better choice?