Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท From Models to Code

State Machines to Code

Turn UML state machine diagrams into code with three techniques: nested switch, transition table and the State pattern, plus tests for every transition.

A state machine diagram is a precise specification, and a precise specification should produce precise code. There are three standard ways to implement one. Each has a point where it works best, and knowing all three lets you pick sensibly. We use a turnstile with a coin slot as the running example because it is tiny but has guards, actions and ignored events.

stateDiagram-v2
    [*] --> Locked
    Locked --> Unlocked : coin / unlock
    Locked --> Locked : push / alarm
    Unlocked --> Locked : push / lock
    Unlocked --> Unlocked : coin / refund

The turnstile: a coin unlocks, a push locks again. A push on a locked gate sounds the alarm and a second coin is refunded.

Technique 1: nested conditionals

The most direct translation is a switch or an if chain on the current state, with another one on the event.

Python Technique 1: switch on state and event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is easy to write and needs no structure. It suits tiny machines, but it grows badly: every new state adds a branch to every method, and it is easy to forget a combination. The compiler cannot tell you that a case is missing, unless you use an enum plus an exhaustive match/switch in a language that checks it.

Technique 2: a transition table

Put the diagram in data instead of control flow. Each row is one arrow: (state, event) -> (target, action). The engine is five lines and never changes.

Python Technique 2: table-driven machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Advantages: the table mirrors the diagram, it can be loaded from a file, and completeness checks come for free, as the last lines show. The weak point is behavior that differs a lot between states. Actions here are just names, so you still need a mapping from action names to code.

Technique 3: the State pattern

In the State pattern each state becomes an object (or class) that implements the events. The context delegates to its current state object. States hold their own entry and exit behavior, and adding a state means adding a class, not editing a big conditional. See State for the full pattern.

Python Technique 3: one class per state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Entry actions fit naturally here (entry runs on every set), and each state class can hold data that only exists in that state, such as a countdown for Unlocked.

Which technique to use

Situation Choice
Three or four states, one-off Conditionals
Many states, mostly different transitions only, rules loaded from config or checked by tools Table
States have rich, different behavior, extra data or entry/exit logic State pattern
Hierarchical and concurrent states, timers A state machine library (XState, Spring Statemachine, Boost.SML, transitions for Python)

Libraries encode composite states, history and parallel regions, which are hard to write by hand. If your diagram uses them, do not reimplement them.

Guards, timers and queued events

Three practical details decide whether an implementation is robust:

  1. Guards are pure functions of the context. Evaluate them before choosing the transition and keep them free of side effects.
  2. Timers (after(30 s)) should be events delivered to the machine, not sleeps inside it, so that the machine stays testable.
  3. Event queue. If an action fires another event while the machine is in the middle of a transition, queue it and process it after the current transition finishes (run-to-completion semantics). Otherwise you get re-entrant surprises.

Testing every arrow

A diagram with N arrows needs at least N tests, plus a few for ignored events. Table-driven tests mirror the table, as in the second example. State transition testing shows how to derive them systematically: cover every state, every transition, and the illegal pairs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of a transition table?

    The table mirrors the diagram and supports automatic checks.
  2. 2. In the State pattern, what does adding a new state usually require?

    Each state is a class; the context stays the same.
  3. 3. How should a timer event such as after(30 s) be implemented?

    Delivering timers as events keeps the machine deterministic and testable.
  4. 4. When a diagram uses composite and concurrent states, what is a sensible choice?

    Hierarchy, regions and history are error-prone to build by hand.

Summary

  • A state machine diagram can be implemented as conditionals, a transition table or the State pattern.
  • Tables suit data-driven, checkable machines; state classes suit rich per-state behavior.
  • Keep guards pure, deliver timers as events and process queued events after each transition.
  • Use a library for hierarchical or concurrent machines.
  • Test every transition and a few ignored events.

Next: Sequence Diagrams to Tests