State pattern
medium 55 minThe State pattern lets an object change its behaviour when its internal state changes.
Video lesson · Chapter 1 of 6
Make a prediction
State pattern
1:06Reel
More reels
One idea each, a minute or less.
State vs strategy
0:33Reel
Theory
Read or listen first. About 2 min.
What it is
The State pattern is a behavioral design pattern. An object, the context, holds a reference to one state object and forwards its events to it. Replace the state object, and the same call does something else.
It is an object-oriented way to write a finite state machine: a thing that is in exactly one of a few states, and moves to another when an event arrives. Each state is a class, each event a method, and each transition the replacement of one reference.
The caller notices none of this. To the caller the object seems to have changed its class.
Why it exists
Without it, each method begins with the question "which state am I in?". The question is copied into every method, the copies drift apart, and combinations that make no sense become possible.
With it, everything that is true in one state stands in one place. You can read, test and review a state alone, and you can add one without reading the others.
It matters most where a wrong answer costs something: money in a vending machine, a published document that must not change, a connection that sends data after closing.
It also gives the team one word and one drawing. "What happens on cancel in Sold?" is a question that product, testers and developers can all answer from the same table.
A short history
1955
George Mealy publishes A Method for Synthesizing Sequential Circuits in the Bell System Technical Journal. Outputs depend on state and input.
1956
Edward Moore's Gedanken-experiments on Sequential Machines: outputs depend on the state alone.
1981
RFC 793 describes TCP with a state diagram from CLOSED to ESTABLISHED and back.
1987
David Harel publishes Statecharts: states inside states, and states side by side, against the explosion of flat diagrams.
1994
The book Design Patterns appears and lists State among its behavioral patterns.
2015
SCXML, a notation for statecharts with entry and exit actions, becomes a W3C Recommendation on 1 September.
2022
RFC 9293 replaces RFC 793. The state machine is still in it.
Words to know
- Context
- The object callers use. It holds the data and the current state.
- State
- A situation in which the object answers events in its own way. Also the interface of all state classes.
- Concrete state
- The class for one state.
- Event
- Something that happens to the object: a call, a message, a timer.
- Transition
- Moving from one state to another because of an event.
- Self transition
- An event that does something and leaves the state as it is.
- Guard
- A condition that decides whether a transition may be taken.
- Entry and exit action
- What runs on every arrival in and every departure from a state.
- Superstate
- A parent state that answers for its children.
- Run to completion
- One event is finished before the next one starts.
- Transient state
- A state that is left soon and by itself, such as Sold.
- Extended state
- Data beside the state, such as the balance.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Event arrives. The context forwards it to the current state
Understand it
Start here
One machine, several moods
Press button A on a vending machine. Sometimes a cola falls. Sometimes nothing happens. The button is the same. What changed is the state of the machine: whether it holds your money, whether its motor is running, whether it is empty. The pattern on this page is about code that behaves like that.
Nobody rebuilt the panel between two pictures. The buttons always pass the press on to whichever mood is in charge.
Three parts
Context
The object that people use:
VendingMachine,TcpConnection,MediaPlayer,Document. It holds one current state and passes every event to it.State
An interface with one method per event. It usually receives the context, so that a state can ask for a transition.
Concrete states
One class per state:
NoCoin,HasCoin,Sold. Each holds everything that is true only in that state.
Why
What goes wrong without it
The first version of such a class usually has a few flags. It looks fine on the day it is written.
class VendingMachine: def __init__(self): self.has_coin = False self.is_dispensing = False self.is_sold_out = False self.balance = 0 self.coin_tray = 0 def insert_coin(self, cents): if self.is_sold_out or self.is_dispensing: self.coin_tray += cents else: self.balance += cents self.has_coin = True def select_product(self, price): if self.is_sold_out: print("SOLD OUT") elif self.is_dispensing: print("ALREADY DISPENSING") elif not self.has_coin: print("INSERT COIN FIRST") elif self.balance < price: print("PRICE", price) else: self.is_dispensing = True def cancel(self): if self.has_coin: # nobody thought of is_dispensing self.coin_tray += self.balance self.balance = 0 self.has_coin = False def dispense(self, price): if self.is_dispensing: self.coin_tray += max(0, self.balance - price) self.balance = 0 self.is_dispensing = False self.has_coin = Falsem = VendingMachine()m.insert_coin(200)m.select_product(150) # the motor startsm.cancel() # all the money comes backm.dispense(150) # and the cola falls anywayprint("paid 200, back", m.coin_tray, "and a free cola")Nobody wrote a wrong line. cancel checks has_coin, and while the motor turns has_coin is still true. The bug is the combination: the programmer of cancel had to remember a flag that belongs to dispense.
Flags multiply
The design that hurts
1/3One class, three flags
Every method begins by working out which situation it is in. The same question is asked in insertCoin, selectProduct, cancel and dispense.
uses
One class per state
- Everything about a state is in one place
- A new state is a new class, plus the places that lead to it
- Abstract methods make the compiler ask for every event
- You can read, test and review one state alone
Conditions on a state field
- The same
iforswitchin every method - A new state means editing every method
- Easy to miss one case, and nothing tells you
- To understand one state you read the whole class
The idea
Replace the question by an object
Instead of asking "which state am I in?" again and again, keep the answer in one field, and let the answer do the work. The field holds an object. Each method of the context becomes one line: hand the event to that object.
The State pattern in general
1/4Client and context
Callers know the context and nothing else. They never see a state class.
useshas (lives on)implements
Two presses, the same code, two answers
state.selectProduct(this, code) both times. This is polymorphism: the caller does not know which class answers.From flags to states
Another picture
The crossing
A traffic light has one colour at a time. Red: cars stop and people walk. Green: cars go and people wait. It is the same light, and each colour knows two things: what is allowed now, and which colour comes next.
30 + 45 + 5 = 80 seconds for one round. The code of this light is in the solution, under entry and exit actions.
The light as a state diagram
The light as classes
1/3What road users see
A car or a walker asks one light two yes or no questions.
usesowns (dies together)extends (is a)
Transitions
Who decides what comes next?
Somebody has to replace the state. There are three usual places, and an interviewer will ask for your reason.
| Who decides | Code | Good | Costs |
|---|---|---|---|
| The state | m.go(m.has_coin) inside NoCoin | The condition sits next to the behaviour. Easy to follow one state | States know each other. The whole picture is spread over the classes |
| The context | if result == PAID: self.go(...) | States know nothing about their neighbours, so they can be reused | The conditions you removed come back into the context |
| A table | NEXT[(state, event)] | The whole machine on one screen, easy to check and draw | Rich behaviour per state needs functions in the table |
| The state returns it | return m.green, the context switches | One place changes the field, so entry, exit and logging cannot be forgotten | Every handler must return something |
go method. Both have exactly one line that writes the field.A new requirement: when everything is sold, the machine must say SOLD OUT. Where does that go?
BreaksA flag is_sold_out, checked where needed
- How
- Add a boolean and an
ifat the top of each method. - Limit
- Four methods to edit, and impossible combinations: sold out and dispensing at once.
- Choose when
- Never, once there are states already.
WorksA check inside NoCoin
- How
NoCoin.insert_coinlooks at the stock and gives the coin back.- Limit
NoCoinnow has two behaviours in one class. The same check follows inselect_product.- Choose when
- If the only difference is one message.
StrongA state SoldOut
- How
- One new class.
Sold.dispensegoes there when the stock is empty, andrefillleads back toNoCoin. - Limit
- Not free: one class, one field in the machine, one changed line in
Sold, and one new event. - Choose when
- When several events are answered differently. That is the definition of a state.
Choosing
When to use it and when not
Use it when
- What an object does depends on its state
- Several methods ask the same state question
- The transitions are known and can be drawn
- You are implementing a state machine whose states have real behaviour
- States are likely to be added
Leave it when
- There are two or three states with one line each
- The states hardly ever change
- Only data differs: use a table
- The state is only shown, never acted on
- It adds more classes than it removes conditions
Enum, table or classes?
Real cases
| Object | States | Typical event that differs |
|---|---|---|
| TCP connection | CLOSED, LISTEN, SYN-SENT, ESTABLISHED, FIN-WAIT-1 and more | close: ESTABLISHED sends a FIN, LISTEN only forgets |
| Button on a screen | normal, hover, pressed, disabled | release: pressed fires the click, disabled does nothing |
| Order | New, Paid, Shipped, Delivered, Cancelled | cancel: before shipping yes, after it no |
| Game character | idle, walking, running, jumping, attacking | jump: standing jumps, jumping ignores it or jumps twice |
| Media player | stopped, playing, paused | the one big button |
| Document | draft, review, published | edit: draft yes, published no |
A TCP connection, the side that closes first
interface TcpState { open(c: TcpConnection): void; close(c: TcpConnection): void; acknowledge(c: TcpConnection): void;}class TcpConnection { state: TcpState = CLOSED; open() { this.state.open(this); } close() { this.state.close(this); } acknowledge() { this.state.acknowledge(this); } send(flag: "SYN" | "FIN" | "ACK") { /* put a segment on the wire */ }}const ESTABLISHED: TcpState = { open() { throw new Error("connection already exists"); }, close(c) { c.send("FIN"); c.state = FIN_WAIT_1; }, acknowledge() { /* data arrived, stay */ },};close in ESTABLISHED sends a FIN and moves to FIN-WAIT-1 (RFC 9293). In LISTEN there is nobody to tell.The price
More classes
Four states and five events are twenty small methods. For three lines of behaviour that is too much.
The picture is spread out
No single file shows all transitions. Keep the state diagram in the repository and test against a table.
States know each other
If
NoCoinnamesHasCoin, removingHasCoinbreaksNoCoin. That is honest, not free.A new event is expensive
A new state adds one class. A new event adds one method to every state. Know which of the two your problem grows by.
Summary
The whole topic in one minute.
Draw the states and the events, and answer each cell of the table. Context forwards, states decide, one method writes the state field. Data that outlives a state lives in the context.
Refuse completely: a refused coin is returned. Guards ask, entry and exit belong to the state. A new state is one class and the lines that lead to it, a new event touches all states.
In production: one event at a time, conditional updates, stored names with versions, ids for events, a log that can be replayed, and a test that visits every cell. If only the allowed moves differ, use an enum and a table.
- If several methods ask "which state am I in?", turn the answer into an object.
- Context, State interface, one class per state. The context delegates, the states decide.
- Let exactly one method write the state field. Logging, entry, exit and tests hang on it.
- Draw the state and event table first. Every cell needs an answer, also "refuse".
- A new state is one class and the lines that lead to it. A new event touches every state.
- State changes itself from inside. Strategy is chosen from outside.
Sources
- RFC 9293: Transmission Control Protocol, state machine overview
- W3C: State Chart XML (SCXML)
- David Harel: Statecharts, a visual formalism for complex systems (PDF)
- George Mealy: A Method for Synthesizing Sequential Circuits (1955)
- Design Patterns (publisher's page)
- Android: MediaPlayer state diagram
- Spring Statemachine reference
- PostgreSQL: transaction isolation
- AWS Step Functions: StartExecution