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.
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.
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:
...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 booleans | Exactly one state at a time |
| Impossible combinations possible | Only legal states, by design |
| Scattered if-checks | One clear 'can I do X?' question |
| Ad-hoc, buggy transitions | Explicit, 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.
Related lessons
Separation of Concerns
The most important design idea of all: keep different responsibilities in different placesโฆ
Software Design & ArchitectureDecoupling with Events
When everything is directly wired to everything, one change ripples everywhere. Events letโฆ
Data Structures & AlgorithmsWhy Data Structures Matter
How you store data decides how easy - and how fast - everything else becomes. Choosing theโฆ