State machines in practice: transition tables, guards and event logs
Model order statuses, CSV quoting and regex matching as state machines: one transition table, guards for business rules, event logs you can replay, and NFAs that track several states.
A state machine is a value that can only be in one of a few states, plus rules for which events move it from one state to another. Once you spot them, they're everywhere: order statuses, parsers, network connections, UI flows, regular expressions.
States and events
List them explicitly before writing code:
states: Placed, Paid, Shipped, Delivered, Cancelled, Returned
events: pay, ship, deliver, cancel, returnUse an enum (or your language's equivalent) for each, never strings scattered through the code.
A transition table
Write every allowed transition in one table. Anything not in the table is refused:
(Placed, pay) -> Paid
(Placed, cancel) -> Cancelled
(Paid, ship) -> Shipped
(Paid, cancel) -> Cancelled
(Shipped, deliver) -> Delivered
(Delivered, return) -> ReturnedIn C++ that's a std::map<std::pair<Status, Event>, Status>, or a switch inside one function.
The point is one place that decides. A refused transition should leave the state untouched
and report why: "can't ship an order that is Placed".
Test it exhaustively: loop over every state × event pair and compare with the table. With 6 states and 5 events that's 30 cases, and that loop catches mistakes no hand-picked test will.
Guards
Some transitions depend on data, not just on the current state: "a return is only allowed within 30 days of delivery". That's a guard, a condition checked after the table says "allowed":
function apply(order, event, date):
next = table.lookup(order.status, event) or refuse "not allowed from <status>"
if date < order.last_change_date: refuse "dates can't go backwards"
if event == return and date > order.delivered_on + 30 days: refuse "return window closed"
order.status = next; order.history.append((event, date))Check every guard before changing anything, so a refused event leaves no trace.
Event logs and replay
If you store the events instead of only the current status, you get history for free, and you can
rebuild any order by replaying its events from the start through the same apply function:
order = new Order()
for each event in log: apply(order, event) # must succeed, or the log is corruptReplay uses the same rules as live updates, so a log can never produce a state the rules forbid. That's the idea behind event sourcing, audit trails and database write-ahead logs. Build it in order lifecycle for Shipwright.
Parsers as state machines
Splitting a CSV line looks like a job for split(',') until a field contains a comma inside
quotes. Walk the characters with a state instead:
states: StartOfField, InUnquoted, InQuoted, QuoteInQuoted
InQuoted + '"' -> QuoteInQuoted (end of field, or the first half of "")
QuoteInQuoted + '"' -> InQuoted, append '"'
QuoteInQuoted + ',' -> end field, StartOfField
QuoteInQuoted + other -> error "unexpected character after closing quote"
end of line in InQuoted -> error "unterminated quote"Each error knows exactly where and why. Build it in weekly sales report for Market Square.
NFAs: being in several states at once
A regular expression compiles to a state machine where one character can lead to several
next states (in a*ab, an a could belong to the loop or to the literal). That's a
non-deterministic finite automaton (NFA).
Backtracking engines try one option, then go back and try the other, which can take exponential
time on inputs like (a*)*b against aaaa…a. The safe way is to track the set of states
you could be in:
current = epsilon-closure({start})
for each character c:
current = epsilon-closure({ next(s, c) for s in current })
match if current contains the accepting stateEach character costs at most the number of states, so matching is linear in the text, always. Building the NFA from the parsed pattern is called Thompson's construction. See a safe regex engine for Sieve Mail.
Questions and answers
- Why use a transition table instead of if statements?
- A table puts every allowed change in one place, where you can read it, review it against the ticket and test it exhaustively. Scattered if statements drift apart, and an illegal transition slips through in the one path nobody checked.
- What is the difference between a DFA and an NFA?
- A DFA is in exactly one state at a time. An NFA can be in several at once, because a character can lead to more than one next state. Simulating an NFA by tracking the set of current states matches in linear time without backtracking.
Practise it in a project
These projects put this guide to work, with tickets, tests and code review.
Shipwright
Order lifecycle for Shipwright
Replace Shipwright's tangle of status flags with an explicit state machine: one transition table, guards, an audit history and replay from an event log.
- finite state machines
- transition tables
- guards
- event replay
Market Square
Weekly sales report for Market Square
Parse Market Square's sales export, quotes and all, and turn it into revenue per category without letting one bad row spoil the report.
- state machines
- CSV quoting
- error reporting
- aggregation
Sieve Mail
A safe regex engine for Sieve Mail
Write the regular-expression engine behind Sieve Mail's filter rules: a parser, Thompson's NFA construction and a simulation that runs in linear time, so no rule can hang the mail servers.
- parsing
- automata
- Thompson's construction
- worst-case complexity
Tracehound
Log analysis for Tracehound
Parse structured log lines, quoted values and all, then compute error rates and p95 latencies so on-call engineers find the slow endpoint in seconds.
- tokenising
- key-value parsing
- percentiles
- aggregation
Read next
- Recursive descent parsing: tokenizers, grammars and precedence
How to parse formulas, JSON and patterns by hand: split input into tokens, write the grammar down, turn each rule into a function, handle precedence, and report exact error positions.
- Invariants and all-or-nothing updates: keeping data consistent
Name the rules your data must always obey, enforce them in one place, validate everything before changing anything, keep history append-only, and test invariants with random operations.
- How to work with tickets and acceptance criteria as a junior developer
How to read a ticket, find what it doesn't say, ask good questions, and turn acceptance criteria into tests, with examples from realistic product tickets.