Concept

State Machine

Definition

A state machine is a model of computation in which the system is, at any moment, in exactly one of a finite set of states. Events arrive from the outside world or from internal timers, and a transition table specifies which state the machine moves to next given its current state and the incoming event. Anything not in the table is, by construction, impossible — and that constraint is the source of the model's reliability.

The pattern shows up everywhere stateful behaviour must be auditable: an order's lifecycle through new, open, partially filled, filled, cancelled, and rejected; a TCP connection's handshake; a UI component cycling through idle, loading, success, and error. Drawing the diagram once is often the cheapest way to discover that the implementation had a phantom path no one had considered.

Why it matters

How it works

The minimal definition has four elements: a set of states, a set of input events, a transition function mapping (state, event) to next state, and a designated initial state. Extended variants add entry and exit actions per state, internal events that fire as side effects, hierarchical or nested states for shared substructure, and guard conditions that gate transitions on extra context. The richer the variant, the closer the model gets to what Harel called statecharts — the formalism that powers many UI frameworks and embedded protocols today.

In practice the model is implemented either as a transition table — a two-dimensional lookup keyed by current state and event — or as a switch on the current state inside an event handler. The table form is preferable for anything beyond a few states because it forces the developer to think about every cell and surfaces missing transitions as gaps rather than silent fall-throughs. Property-based tests can then enumerate every (state, event) pair and assert that the resulting next state is the documented one, which catches regression bugs that ad-hoc conditional logic typically misses.

Where it goes next

Continue exploring

Tags