LESSON 3.4
State diagrams
A state diagram makes implicit control flow explicit. If an object behaves differently in different situations, it has states — name them.
7 min read
A vending machine starts with one boolean: dispensing. Then a second appears: outOfStock. Then a third: awaitingChange. Three booleans give eight combinations. Most are unreachable, but the code must handle them. A state diagram gives each reachable combination a name and allows only the transitions that make sense.
The problem
class VendingMachine {
#dispensing = false;
#paid = false;
insertCoin() {
if (this.#dispensing) return "busy"; // Informal state guarded by flags.
this.#paid = true;
return "coin accepted";
}
select(item) {
if (!this.#paid || this.#dispensing) return "not ready";
this.#dispensing = true;
this.#paid = false;
// ... dispense item
this.#dispensing = false;
return `dispensed ${item}`;
}
}
// Every new requirement adds another flag and another combination to test.Three flags, four combinations, and the code never states which combinations are reachable. Adding "out of stock" means checking three flags together.
The state machine
Name the reachable states: IDLE, HAS_COIN, DISPENSING. Define what happens on each event in each state. Events that have no valid transition in the current state either throw or are silently ignored.
In code
Guards and actions
A state transition has three parts: the event that triggers it, an optional guard condition that must be true, and an optional action performed during the transition.
insertCoin [amount > 0] / coins += amount reads: On insertCoin, if amount > 0, add to coins and move to HAS_COIN. Guards make illegal inputs first-class citizens of the model, not afterthoughts in if-statements.
Where you have already seen it
React's useReducer is a state machine: state + action → next state. XState and Redux toolkit model state explicitly. TCP's connection lifecycle (LISTEN → SYN_RCVD → ESTABLISHED → TIME_WAIT → CLOSED) is a state machine diagram in the RFC. Order statuses in e-commerce systems are informal state machines that benefit from explicit modeling.
Try it
Vending Machine LLD
Draw the state diagram with named states, transitions and guards before writing a single method.