AlgoViz

State pattern

medium 55 min

The State pattern lets an object change its behaviour when its internal state changes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

State pattern

1:06Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1955

    George Mealy publishes A Method for Synthesizing Sequential Circuits in the Bell System Technical Journal. Outputs depend on state and input.

  2. 1956

    Edward Moore's Gedanken-experiments on Sequential Machines: outputs depend on the state alone.

  3. 1981

    RFC 793 describes TCP with a state diagram from CLOSED to ESTABLISHED and back.

  4. 1987

    David Harel publishes Statecharts: states inside states, and states side by side, against the explosion of flat diagrams.

  5. 1994

    The book Design Patterns appears and lists State among its behavioral patterns.

  6. 2015

    SCXML, a notation for statecharts with entry and exit actions, becomes a W3C Recommendation on 1 September.

  7. 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.

Step 1 of 3

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.

Asha and the machine with moods
Waiting$Aaccept itrefusenothingINSERT COINABC

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.

Python
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")
Run it. Press cancel while the motor turns, and the machine gives the money back and the cola too.
Edit and run it in your browser

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

23=8 combinations of three flags4 of them mean something2^3 = 8 \text{ combinations of three flags} \qquad 4 \text{ of them mean something}
Waiting, has coin, dispensing, sold out. The other four, for example sold out and dispensing, should never exist, but nothing in the code forbids them. A fourth flag makes it 16.

The design that hurts

VendingMachine- hasCoin: bool- isDispensing: bool- isSoldOut: bool- balance: int+ insertCoin(): 2 ifs+ selectProduct(): 4 ifs+ cancel(): 1 if+ dispense(): 1 if

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

The smell: the same condition about the same field in many methods.

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 if or switch in 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

Client+ calls request()Context- state: State+ request()+ setState(s: State)

1/4Client and context

Callers know the context and nothing else. They never see a state class.

useshas (lives on)implements

Each event that the states answer differently becomes one method of the interface. Events with the same answer everywhere stay in the context.

Two presses, the same code, two answers

The line of code in the machine is state.selectProduct(this, code) both times. This is polymorphism: the caller does not know which class answers.

From flags to states

The strongest argument is on the no path: a field that holds one state object can not be sold out and dispensing at once.

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.

The light on State Street
22WALK

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

Night never begins in the middle of green: first the cars get their yellow.

The light as classes

RoadUser+ asks the lightTrafficLight- state: LightState- left: int- walkLamp: bool+ tick()+ canIDrive(): bool+ canIStartWalking()

1/3What road users see

A car or a walker asks one light two yes or no questions.

usesowns (dies together)extends (is a)

Here the filled diamond is right: this light builds its own three states and they go away with it.

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 decidesCodeGoodCosts
The statem.go(m.has_coin) inside NoCoinThe condition sits next to the behaviour. Easy to follow one stateStates know each other. The whole picture is spread over the classes
The contextif result == PAID: self.go(...)States know nothing about their neighbours, so they can be reusedThe conditions you removed come back into the context
A tableNEXT[(state, event)]The whole machine on one screen, easy to check and drawRich behaviour per state needs functions in the table
The state returns itreturn m.green, the context switchesOne place changes the field, so entry, exit and logging cannot be forgottenEvery handler must return something
The traffic light uses the last one, the vending machine the first one through a single 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 if at 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_coin looks at the stock and gives the coin back.
Limit
NoCoin now has two behaviours in one class. The same check follows in select_product.
Choose when
If the only difference is one message.
StrongA state SoldOut
How
One new class. Sold.dispense goes there when the stock is empty, and refill leads back to NoCoin.
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?

Start at the top. Most order workflows end at the table. Machines, protocols and players end at the classes.

Real cases

ObjectStatesTypical event that differs
TCP connectionCLOSED, LISTEN, SYN-SENT, ESTABLISHED, FIN-WAIT-1 and moreclose: ESTABLISHED sends a FIN, LISTEN only forgets
Button on a screennormal, hover, pressed, disabledrelease: pressed fires the click, disabled does nothing
OrderNew, Paid, Shipped, Delivered, Cancelledcancel: before shipping yes, after it no
Game characteridle, walking, running, jumping, attackingjump: standing jumps, jumping ignores it or jumps twice
Media playerstopped, playing, pausedthe one big button
Documentdraft, review, publishededit: draft yes, published no

A TCP connection, the side that closes first

A part of the diagram in RFC 9293. Each arrow names an event and what is sent.
TypeScript
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 */ },};
A TCP connection, shortened. 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 NoCoin names HasCoin, removing HasCoin breaks NoCoin. 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