๐Ÿ›๏ธ
๐Ÿ›๏ธ Software Design & Architecture ยท ARCH-101 ยท Session 3 of 6

Modelling with State Machines

A huge amount of app logic is really about *states* and the moves between them. Modelling that explicitly โ€” as a state machine โ€” turns a mess of flags and conditionals into something clear and correct.

โฑ 9 min read๐Ÿ“… Updated 2026-08-06๐Ÿ“Š Tables, charts & examples

Here's a pattern that appears everywhere once you notice it: things that move through states. An order is placed, then paid, then shipped, then delivered. A document is a draft, then in review, then published. Modelling this with scattered boolean flags (is_paid, is_shipped...) and if-statements gets buggy fast. A state machine models it explicitly - the states and the allowed moves between them - which is clearer, and makes illegal states impossible. This session is a practical design pattern you'll reuse constantly.

๐Ÿ“Œ Worked example
The order that was paid, shipped, and cancelled. An app tracked orders with three booleans - is_paid, is_shipped, is_cancelled - and everything worked in testing. Then real orders arrived, and a race of edge cases produced records that were paid AND shipped AND cancelled all at once, delivered orders that were never marked paid, and refunds on things that never shipped - because nothing stopped the impossible combinations, and dozens of scattered if-checks each handled the flags slightly differently. Rewritten as a state machine - placed to paid to shipped to delivered, with cancel only allowed before shipping - the impossible states simply couldn't occur, 'can I cancel this?' became one clear question, and a whole category of bugs vanished by design. Flags let nonsense exist; a state machine forbids it.

The problem with flags

Representing a thing's status with a pile of independent booleans invites contradictions and tangled logic.

# flags: nothing stops impossible combinations
order.is_paid = True
order.is_shipped = True
order.is_cancelled = True   # ...paid, shipped AND cancelled?!

# scattered checks everywhere
if order.is_paid and not order.is_shipped and not order.is_cancelled:
    ...
๐ŸŽฏ
Flags let impossible states exist; a state machine makes them impossible. With separate booleans, nothing stops an order being both 'shipped' and 'cancelled', or 'delivered' before 'paid' - the code allows nonsense, and you end up with defensive checks everywhere trying to prevent it. A state machine says a thing is in exactly one state at a time, and can only move along defined transitions. Now 'paid and cancelled and shipped' simply can't happen, and 'can I ship this?' is one clear question. You've turned a class of bugs into things that can't occur by design.

Model states and transitions explicitly

Instead of flags, name the states and the legal transitions between them - which is exactly what a state machine (like larzfsm) captures.

from larzfsm import Machine

order = Machine("placed", [
    ("pay",     "placed",  "paid"),
    ("ship",    "paid",    "shipped"),
    ("deliver", "shipped", "delivered"),
    ("cancel",  ["placed", "paid"], "cancelled"),
])
order.fire("pay"); order.fire("ship")   # placed -> paid -> shipped
order.can("cancel")                     # False - can't cancel once shipped
Instead of...A state machine gives you...
Many independent booleansExactly one state at a time
Impossible combinations possibleOnly legal states, by design
Scattered if-checksOne clear 'can I do X?' question
Ad-hoc, buggy transitionsExplicit, correct transitions

Modelling the state explicitly makes the logic obvious (you can read the transitions and see exactly how things flow), safer (illegal moves are rejected), and easier to change (add a state or transition in one place). It's one of the highest-value patterns for real app logic.

States, not flag soup

  • Lots of app logic is about states and the moves between them - notice the pattern.
  • Boolean flags allow impossible combinations and scatter checks everywhere.
  • A state machine = exactly one state at a time + only defined transitions (larzfsm).
  • The result is logic that's clear, correct-by-design, and easy to extend.

๐Ÿงฉ Do it with LarzOS

Turn this lesson into action with the exact free tools and AI workflows for the job:

๐ŸŽฏ Key takeaways

  • A lot of app logic is really about things moving through states - a pattern worth recognising.
  • Representing status with independent boolean flags allows impossible combinations and scatters checks everywhere.
  • A state machine says a thing is in exactly one state at a time and can only move along defined transitions (larzfsm).
  • Modelling state explicitly makes logic clear, correct-by-design (illegal moves impossible), and easy to extend.

Frequently asked

How do I recognise when something should be modelled as a state machine?

Look for things that have a status which changes over time through a sequence of steps, especially where only certain changes are valid from each point - that pattern is a state machine waiting to be recognised, and it's remarkably common once you're attuned to it. Concrete signals: you find yourself tracking a 'status' or 'stage' with a value or several boolean flags (is_paid, is_active, is_complete); the thing progresses through recognisable phases (an order: placed, paid, shipped, delivered; a user account: pending, active, suspended, closed; a support ticket: open, in-progress, resolved, closed; a game: menu, playing, paused, over; a form wizard: step 1, step 2, step 3); certain actions are only valid in certain states (you can't ship an unpaid order, can't resume a game that's over, can't edit a published document); and you have conditionals scattered around checking combinations of flags to decide what's allowed. Whenever you notice 'this thing is in one of several states, moves between them in defined ways, and some moves aren't allowed from some states', a state machine models it well. Another tell is if you're writing defensive checks to prevent impossible or invalid combinations (guarding against 'shipped but not paid'), which is a sign you're manually enforcing what a state machine would enforce by design. The boolean-flags smell is a strong indicator: if an entity's condition is represented by multiple independent booleans that in reality can't all combine freely (they're really describing one status with several possible values), that's often better as a single state with a machine governing transitions. To apply it, identify the distinct states (the mutually-exclusive conditions the thing can be in - it's in exactly one), the events/actions that cause changes, and which transitions are legal (from which state, which event, leading to which state) - then a tool like larzfsm captures that directly. Not everything is a state machine, of course - simple data without meaningful status progression, or logic that isn't about a lifecycle, doesn't need one, and forcing the pattern where it doesn't fit is over-engineering. But the pattern fits a large, common class of app logic: lifecycles, workflows, processes, and anything with a status that evolves through allowed steps. A good habit when you catch yourself adding another boolean flag or another check about what's allowed given the current status is to pause and ask 'is this really a set of states with transitions?' - often it is, and modelling it as such turns tangled, bug-prone flag-checking into clear, correct-by-design logic. With practice you'll spot the shape quickly: mutually-exclusive statuses + defined transitions + rules about what's allowed when = model it as a state machine.

Isn't a state machine overkill - can't I just use a status field with an if-statement?

For very simple cases a status field with a few checks is fine and a full state-machine structure would be overkill - but as the states and rules grow, the explicit state machine pays off by preventing bugs and keeping logic manageable, so it's about matching the tool to the complexity. If your thing has just two or three states and trivial, rarely-changing rules about transitions, a simple status field ('draft' or 'published') with a couple of checks is perfectly reasonable, and wrapping it in machinery would add ceremony without much benefit - don't over-engineer the trivial. The state-machine approach earns its keep as complexity rises in recognisable ways: when there are several states and, crucially, real rules about which transitions are legal from which states (you can only ship a paid order, only cancel before shipping, etc.); when getting those rules wrong would cause bugs (impossible combinations, invalid transitions slipping through); when the logic about 'what's allowed now' would otherwise be scattered across many if-statements in different places; and when the states and transitions are likely to change or grow (adding a new state or rule). In those situations, a status field with ad-hoc if-statements tends to degrade: the transition rules live implicitly in scattered conditionals that are easy to get inconsistent, nothing centrally enforces which moves are valid so invalid ones creep in, and understanding or changing the lifecycle means hunting through the code. An explicit state machine addresses all of that: it declares the states and legal transitions in one place (so the lifecycle is visible and enforced centrally), makes illegal transitions impossible by design rather than by remembering to check, turns 'can I do X now?' into one clear question, and lets you add or change states and transitions in that one definition rather than editing checks everywhere. So the honest guidance is: use the simplest thing that works, which for trivial status is just a field and a check; reach for an explicit state machine when you have multiple states with real transition rules, where correctness matters and the logic would otherwise sprawl - which is common in real app workflows (orders, accounts, tickets, processes). The transition point is roughly when you notice the status logic getting complicated, error-prone, or scattered - that's the signal that the state machine structure will make it clearer and safer, and a lightweight tool like larzfsm makes adopting it cheap. It's not that state machines are always better; it's that they're the right tool once the state logic reaches a complexity where implicit-flags-and-ifs become a liability. Recognising that threshold is the judgement to develop - simple status stays simple, but don't let genuinely complex, rule-laden state logic live as tangled conditionals when modelling it explicitly would prevent a whole class of bugs and keep it maintainable.

Session 3 of 6 complete

Next up: Decoupling with Events

Continue to Session 4 โ†’

Related lessons

More in this course

Course home → · Browse all courses →