Commissioned for this museum · after Gamma, Helm, Johnson & Vlissides, 1994

State

TypeScript·1994·31 lines·1175 bytes

Curator’s note

There is not one if in this file asking which state the object is in, and that absence is the exhibit. The alternative — a status field and a switch inside every method — is what this code is in most codebases, and it smears the machine across every function that touches it, so that adding a fourth state means finding and correctly editing all of them.

Here a state simply *is* its set of legal transitions. Look at what idle does not have: no stop. Stopping an already-idle player is not a case to detect and reject; it is a property that does not exist on the object, and the compiler knows it before the program runs. Impossible transitions become impossible to write, rather than possible to write and wrong.

The last line of output is the honest part. stop on idle is undefined, and the loop prints (ignored) rather than crashing — because "this input does nothing in this state" is a real answer a state machine has to have. Pretending otherwise is precisely how these things acquire their bugs.

What the pattern costs is that the machine is now spread across three definitions instead of gathered into one table, and there is no single place to read off every transition. For three states that is a fair trade. For thirty it is why people reach for a state chart and generate the thing instead.