Programming Search⌘K

Patterncore

State pattern

Also called State, Objects for States, state object, state machine.

An object keeps its current state in a separate state object and passes each request to it. A change of state replaces that object, so the object behaves as if its class had changed.

Family
behavioral-design
Intent
Let an object change its behaviour when its internal state changes, so that the object appears to change its class.
Also called
Objects for States
Refactorings
Replace state altering conditionals with state, Replace conditional with polymorphism

Intent

Let an object change its behaviour when its internal state changes. To its clients, the object appears to change its class.1 The object is called the context. It keeps a reference to a state object and passes each request to it. A change of state replaces the state object.

Problem

A TCP connection reacts to the same request in different ways. An open on a closed connection starts a handshake. An open on an established connection is an error. Design Patterns starts from this example.1 The TCP specification lists the states of a connection, from LISTEN and SYN-SENT to TIME-WAIT, and a fictional state CLOSED.3

The first design keeps the state in a field and puts a conditional in each operation. Every method of the connection then starts with the same if or switch on the field. The code for one state is spread over all the methods. To add a state, a programmer must find and change each of them. Design Patterns names this case: operations with large conditional statements that depend on the state of the object, often held in enumerated constants.1

The forces are these. The behaviour for one state should be in one place. The transitions should be visible, not hidden in assignments to a field. And the code that uses the object should not change when a state is added.

Solution

Design Patterns names three participants.1

  • Context is the object that clients use. It holds the current state object and passes each request to it.
  • State declares one operation for each request that depends on the state.
  • ConcreteState implements the behaviour for one state.

A request to the context goes to the current state. The state does its work, and then it either tells the context the next state or returns it. The context does not test the state. The class of the current state object selects the behaviour.

The examples follow a media player with three states and three events. Each line shows the event, the action and the transition:

from enum import Enum


class State(Enum):
    STOPPED = "stopped"
    PLAYING = "playing"
    PAUSED = "paused"


def step(state, event):
    match state, event:
        case State.STOPPED, "play":
            return State.PLAYING, "start at 0:00"
        case State.PLAYING, "pause":
            return State.PAUSED, "hold the position"
        case State.PAUSED, "play":
            return State.PLAYING, "resume"
        case State.PLAYING | State.PAUSED, "stop":
            return State.STOPPED, "rewind"
        case _:
            return state, "ignored"


state = State.STOPPED
for event in ["play", "pause", "play", "stop", "pause"]:
    after, action = step(state, event)
    print(f"{event}: {action} ({state.value} -> {after.value})")
    state = after
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)

This block is not the State pattern. It is an enum and one match statement, and it is the form that the pattern replaces. The Python example file has the same machine with a class for each state. Both forms are correct. The choice depends on what changes more often.

State, an enum and a match

Question State objects Enum and match
Where is the code for one state in one class in one arm of each match
Where are the transitions spread over the state classes in one function, as a table
Add a state add one class add arms to each match
Add an event add a method to each state class add arms to one function
Can the compiler find a missing case yes, when the event methods are abstract yes, when the match must be exhaustive
Can a state hold its own data yes, in its fields yes, in an enum variant with fields

An enum and a match fit a machine with few states, small actions and many readers of the whole table. State objects fit a machine where each state has much code of its own. The Rust book says that an enum design needs a match in each place that checks the state, and that its trait object design avoids this repetition.4

In Rust, a match must cover every value. When the enum gets a variant, each match without a wildcard arm stops compiling.5 This program adds Buffering and forgets its arms:

This code does not compile, on purpose.

#[derive(Clone, Copy)]
enum State {
    Stopped,
    Playing,
    Paused,
    Buffering,
}

fn name(state: State) -> &'static str {
    match state {
        State::Stopped => "stopped",
        State::Playing => "playing",
        State::Paused => "paused",
    }
}

fn main() {
    println!("{}", name(State::Buffering));
}

A wildcard arm _ turns off this check. The Rust example file lists every pair of state and event for this reason.

State and Strategy

The two patterns have the same class diagram. A context holds an object behind an interface and calls it. The difference is who changes the object and how often.

  • A client chooses a strategy, usually once, and the strategies do not know each other.
  • The states change the context's state object while the program runs. A state names the next state, so the state classes depend on each other.

The Strategy pattern page covers strategies. A rule of thumb: if the object is replaced from inside, as a result of its own requests, it is a state.

Who defines the transitions

Design Patterns gives two choices.1 The context can hold the transitions, so that the states do not know each other. Or each state can return or set its successor. The second is more flexible, and it is the form that the example files use. It also makes each state class depend on the others. A third choice is a table that maps a state and an event to the next state. The TypeScript example uses a table. Design Patterns credits this form to Cargill. It says that a table lets a programmer change the transitions by changing data and not code. It also says that a lookup is often slower than a function call, that the uniform table makes the transition criteria harder to understand, and that it is hard to add actions to the transitions.1

Typestate

In a language with generics, each state can be a type. A method that is wrong for a state does not exist on that type, so the wrong call is a compile error. The Rust book calls this encoding states and behaviour as types.4 Each method consumes the player and returns the player in the next state:

This code does not compile, on purpose.

use std::marker::PhantomData;

struct Stopped;
struct Playing;
struct Paused;

struct Player<S> {
    position: u32,
    state: PhantomData<S>,
}

impl Player<Stopped> {
    fn new() -> Self {
        Player { position: 0, state: PhantomData }
    }
    fn play(self) -> Player<Playing> {
        Player { position: 0, state: PhantomData }
    }
}

impl Player<Playing> {
    fn pause(self) -> Player<Paused> {
        Player { position: self.position, state: PhantomData }
    }
}

fn main() {
    let stopped = Player::new();
    let playing = stopped.play();
    let _paused = playing.pause();
    let again = Player::new();
    again.pause(); // a stopped player has no pause method
}

The cost is that the state is no longer a value. A program that reads events from a user does not know the next state at compile time. It needs an enum of the typestates, and so it needs a match again.

Example

All the example files run one script: play, pause, play, stop, and then pause on a stopped player, which is ignored.

Language Form
Python a class for each state; one shared object of each class
JavaScript an object for each state, with a default prototype
TypeScript a transition table typed by unions of string literals
Java an enum whose constants have their own method bodies
C# an enum and a switch expression on the pair of state and event
Go an empty struct for each state and an embedded struct of defaults
Rust an enum and a match that lists every pair
C++ an abstract class, a subclass for each state, and const global state objects
Bash a case on the string "state:event"
PythonGitHub
class State:
    name = ""

    # The default for each event: stay in this state and do nothing.
    def play(self):
        return self, "ignored"

    def pause(self):
        return self, "ignored"

    def stop(self):
        return self, "ignored"


class Stopped(State):
    name = "stopped"

    def play(self):
        return PLAYING, "start at 0:00"


class Playing(State):
    name = "playing"

    def pause(self):
        return PAUSED, "hold the position"

    def stop(self):
        return STOPPED, "rewind"


class Paused(State):
    name = "paused"

    def play(self):
        return PLAYING, "resume"

    def stop(self):
        return STOPPED, "rewind"


# The states hold no data, so one object of each class serves every player.
STOPPED, PLAYING, PAUSED = Stopped(), Playing(), Paused()


class Player:
    def __init__(self):
        self.state = STOPPED

    def play(self):
        self._change("play", *self.state.play())

    def pause(self):
        self._change("pause", *self.state.pause())

    def stop(self):
        self._change("stop", *self.state.stop())

    def _change(self, event, after, action):
        print(f"{event}: {action} ({self.state.name} -> {after.name})")
        self.state = after


player = Player()
player.play()
player.pause()
player.play()
player.stop()
player.pause()
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. A class for each state, with one method for each event. Each method returns the next state and the action, and the player stores the next state.
  • The base class State gives the default for every event. A state class overrides only the events that it handles.
  • The three state objects are module constants. They hold no data, so all players can share them, as the Flyweight note of Design Patterns describes.
  • The node page shows the same machine as an Enum and a match statement.
#include <iostream>
#include <string_view>
#include <utility>

struct State;
using Transition = std::pair<const State*, std::string_view>;

// The base class gives the default for each event: stay and do nothing.
struct State {
    virtual ~State() = default;
    virtual std::string_view name() const = 0;
    virtual Transition play() const { return {this, "ignored"}; }
    virtual Transition pause() const { return {this, "ignored"}; }
    virtual Transition stop() const { return {this, "ignored"}; }
};

struct Stopped final : State {
    std::string_view name() const override { return "stopped"; }
    Transition play() const override;
};

struct Playing final : State {
    std::string_view name() const override { return "playing"; }
    Transition pause() const override;
    Transition stop() const override;
};

struct Paused final : State {
    std::string_view name() const override { return "paused"; }
    Transition play() const override;
    Transition stop() const override;
};

// One shared object for each state. They hold no data, so all players can use them.
const Stopped stopped{};
const Playing playing{};
const Paused paused{};

Transition Stopped::play() const { return {&playing, "start at 0:00"}; }
Transition Playing::pause() const { return {&paused, "hold the position"}; }
Transition Playing::stop() const { return {&stopped, "rewind"}; }
Transition Paused::play() const { return {&playing, "resume"}; }
Transition Paused::stop() const { return {&stopped, "rewind"}; }

class Player {
public:
    void play() { change("play", state_->play()); }
    void pause() { change("pause", state_->pause()); }
    void stop() { change("stop", state_->stop()); }

private:
    void change(std::string_view event, Transition t) {
        std::cout << event << ": " << t.second << " (" << state_->name() << " -> "
                  << t.first->name() << ")\n";
        state_ = t.first;
    }

    const State* state_ = &stopped;
};

int main() {
    Player player;
    player.play();
    player.pause();
    player.play();
    player.stop();
    player.pause();
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. This is the class structure of Design Patterns: an abstract State with a virtual function for each event, and one subclass for each state.
  • The state objects are const globals, and the player holds a pointer to one of them. No state is made or destroyed at run time.
  • The member functions are defined after the three objects, because each state refers to the others. A declaration of each class comes first, and the definitions follow.
  • std::variant with std::visit is the other common form. It keeps the states in one closed type, as the Rust enum does.
JavaGitHub
public class Main {
    record Transition(State next, String action) {}

    enum State {
        STOPPED {
            @Override
            Transition play() {
                return new Transition(PLAYING, "start at 0:00");
            }
        },
        PLAYING {
            @Override
            Transition pause() {
                return new Transition(PAUSED, "hold the position");
            }

            @Override
            Transition stop() {
                return new Transition(STOPPED, "rewind");
            }
        },
        PAUSED {
            @Override
            Transition play() {
                return new Transition(PLAYING, "resume");
            }

            @Override
            Transition stop() {
                return new Transition(STOPPED, "rewind");
            }
        };

        // The defaults: each event is ignored unless a constant overrides it.
        Transition play() {
            return new Transition(this, "ignored");
        }

        Transition pause() {
            return new Transition(this, "ignored");
        }

        Transition stop() {
            return new Transition(this, "ignored");
        }
    }

    static final class Player {
        private State state = State.STOPPED;

        void play() {
            change("play", state.play());
        }

        void pause() {
            change("pause", state.pause());
        }

        void stop() {
            change("stop", state.stop());
        }

        private void change(String event, Transition t) {
            System.out.printf("%s: %s (%s -> %s)%n", event, t.action(), name(state), name(t.next()));
            state = t.next();
        }

        private static String name(State s) {
            return s.name().toLowerCase();
        }
    }

    public static void main(String[] args) {
        Player player = new Player();
        player.play();
        player.pause();
        player.play();
        player.stop();
        player.pause();
    }
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. An enum constant can have a class body, and the body can override the methods of the enum. Each constant is then a state object with its own behaviour.
  • The enum has exactly one object for each constant, so the state objects are shared, and == compares them.
  • The methods in the class bodies refer to the other constants. This is allowed, because a method body runs after the class has made all its constants.
  • A switch over the enum is the other usual form. A switch expression that has a case for each constant is exhaustive and needs no default.
var player = new Player();
foreach (var e in new[] { Event.Play, Event.Pause, Event.Play, Event.Stop, Event.Pause })
{
    player.Handle(e);
}

enum State { Stopped, Playing, Paused }

enum Event { Play, Pause, Stop }

sealed class Player
{
    public State Current { get; private set; } = State.Stopped;

    public void Handle(Event e)
    {
        // One switch expression holds the whole transition table.
        var (next, action) = (Current, e) switch
        {
            (State.Stopped, Event.Play) => (State.Playing, "start at 0:00"),
            (State.Playing, Event.Pause) => (State.Paused, "hold the position"),
            (State.Paused, Event.Play) => (State.Playing, "resume"),
            (State.Playing or State.Paused, Event.Stop) => (State.Stopped, "rewind"),
            _ => (Current, "ignored"),
        };
        Console.WriteLine($"{Name(e)}: {action} ({Name(Current)} -> {Name(next)})");
        Current = next;
    }

    static string Name<T>(T value) where T : Enum => value.ToString().ToLowerInvariant();
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. The states are an enum, and a switch expression on the pair (Current, e) gives the next state and the action. Each arm is one row of a transition table.
  • The or pattern joins two states that react to Stop in the same way.
  • The _ arm gives the default for every pair that the other arms do not match. A C# enum can hold any value of its underlying type, so a switch on an enum without a _ arm gets warning CS8524, even when each named member has an arm.
  • When each state needs its own data or its own code, a class for each state that implements one interface is the classic form.
JavaScriptGitHub
// The prototype of every state: each event is ignored unless a state overrides it.
const base = {
  play() {
    return [this, "ignored"];
  },
  pause() {
    return [this, "ignored"];
  },
  stop() {
    return [this, "ignored"];
  },
};

const stopped = Object.create(base);
const playing = Object.create(base);
const paused = Object.create(base);

Object.assign(stopped, {
  name: "stopped",
  play: () => [playing, "start at 0:00"],
});
Object.assign(playing, {
  name: "playing",
  pause: () => [paused, "hold the position"],
  stop: () => [stopped, "rewind"],
});
Object.assign(paused, {
  name: "paused",
  play: () => [playing, "resume"],
  stop: () => [stopped, "rewind"],
});

class Player {
  state = stopped;

  handle(event) {
    const [after, action] = this.state[event]();
    console.log(`${event}: ${action} (${this.state.name} -> ${after.name})`);
    this.state = after;
  }
}

const player = new Player();
for (const event of ["play", "pause", "play", "stop", "pause"]) {
  player.handle(event);
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. Each state is a plain object. Object.create(base) makes base its prototype, so a state that has no method for an event finds the default in base.
  • The states are made first and filled in later with Object.assign, because each state refers to the others.
  • this.state[event]() looks up the method by the name of the event. A name with no method throws a TypeError, so the caller must send only known events.
TypeScriptGitHub
type StateName = "stopped" | "playing" | "paused";
type EventName = "play" | "pause" | "stop";
type Transition = { next: StateName; action: string };

// The transition table. Record<StateName, ...> makes the compiler ask for a row for each state.
const table: Record<StateName, Partial<Record<EventName, Transition>>> = {
  stopped: {
    play: { next: "playing", action: "start at 0:00" },
  },
  playing: {
    pause: { next: "paused", action: "hold the position" },
    stop: { next: "stopped", action: "rewind" },
  },
  paused: {
    play: { next: "playing", action: "resume" },
    stop: { next: "stopped", action: "rewind" },
  },
};

class Player {
  state: StateName = "stopped";

  handle(event: EventName): void {
    const transition = table[this.state][event] ?? { next: this.state, action: "ignored" };
    console.log(`${event}: ${transition.action} (${this.state} -> ${transition.next})`);
    this.state = transition.next;
  }
}

const player = new Player();
const events: EventName[] = ["play", "pause", "play", "stop", "pause"];
for (const event of events) {
  player.handle(event);
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. This is the table-driven form. The states and events are unions of string literals, and the transitions are data in one table.
  • Record<StateName, ...> needs a key for each state, so tsc rejects a table that leaves out a state. Partial lets a row leave out events, and the ?? gives those events the default.
  • A table fits when the behaviour of a state is only "go to the next state". When each state needs its own code, a function or an object for each state fits better.
package main

import "fmt"

// A State reacts to each event. A nil result means "stay in this state".
type State interface {
	Name() string
	Play() (State, string)
	Pause() (State, string)
	Stop() (State, string)
}

// ignore gives the default for each event. A state embeds it and overrides what it handles.
type ignore struct{}

func (ignore) Play() (State, string)  { return nil, "ignored" }
func (ignore) Pause() (State, string) { return nil, "ignored" }
func (ignore) Stop() (State, string)  { return nil, "ignored" }

type stopped struct{ ignore }
type playing struct{ ignore }
type paused struct{ ignore }

func (stopped) Name() string           { return "stopped" }
func (stopped) Play() (State, string)  { return playing{}, "start at 0:00" }
func (playing) Name() string           { return "playing" }
func (playing) Pause() (State, string) { return paused{}, "hold the position" }
func (playing) Stop() (State, string)  { return stopped{}, "rewind" }
func (paused) Name() string            { return "paused" }
func (paused) Play() (State, string)   { return playing{}, "resume" }
func (paused) Stop() (State, string)   { return stopped{}, "rewind" }

type Player struct{ state State }

func (p *Player) handle(event string, react func(State) (State, string)) {
	next, action := react(p.state)
	if next == nil {
		next = p.state
	}
	fmt.Printf("%s: %s (%s -> %s)\n", event, action, p.state.Name(), next.Name())
	p.state = next
}

func main() {
	p := &Player{state: stopped{}}
	p.handle("play", State.Play)
	p.handle("pause", State.Pause)
	p.handle("play", State.Play)
	p.handle("stop", State.Stop)
	p.handle("pause", State.Pause)
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. Each state is an empty struct that satisfies the State interface. An empty struct has size zero, so making a state value costs nothing.
  • A state struct embeds ignore, so it gets the default methods. The methods that the state declares itself win over the embedded ones.
  • An embedded method cannot return "this state", because it does not know the outer struct. The default methods therefore return nil, and the player reads nil as "stay".
  • State.Play is a method expression. It is a function that takes the receiver as its first argument, so one handle method serves all three events.
RustGitHub
#[derive(Clone, Copy, Debug)]
enum State {
    Stopped,
    Playing,
    Paused,
}

#[derive(Clone, Copy, Debug)]
enum Event {
    Play,
    Pause,
    Stop,
}

fn next(state: State, event: Event) -> (State, &'static str) {
    use Event::*;
    use State::*;
    // No wildcard arm: each pair is listed, so a new state or event needs new arms.
    match (state, event) {
        (Stopped, Play) => (Playing, "start at 0:00"),
        (Stopped, Pause | Stop) => (Stopped, "ignored"),
        (Playing, Pause) => (Paused, "hold the position"),
        (Playing, Play) => (Playing, "ignored"),
        (Paused, Play) => (Playing, "resume"),
        (Paused, Pause) => (Paused, "ignored"),
        (Playing | Paused, Stop) => (Stopped, "rewind"),
    }
}

fn name<T: std::fmt::Debug>(value: T) -> String {
    format!("{value:?}").to_lowercase()
}

fn main() {
    let mut state = State::Stopped;
    for event in [Event::Play, Event::Pause, Event::Play, Event::Stop, Event::Pause] {
        let (after, action) = next(state, event);
        println!("{}: {action} ({} -> {})", name(event), name(state), name(after));
        state = after;
    }
}
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: native. An enum and a match on the pair (state, event) hold the whole machine in one function.
  • The match has no _ arm. The compiler checks that the arms cover every pair, so a state added to the enum stops the build until each event has an arm for it. The node page shows this error.
  • The function is pure. It takes a state and an event and returns the next state, so a test can call it with no player object.
  • The Rust book builds the same kind of machine with trait objects and then with a distinct type for each state. With distinct types, a call that is wrong for the state is a compile error.
BashGitHub
#!/usr/bin/env bash
set -euo pipefail

state=stopped

# One case statement on "state:event" is the transition table.
handle() {
  local event=$1 next action
  case "$state:$event" in
    stopped:play) next=playing action="start at 0:00" ;;
    playing:pause) next=paused action="hold the position" ;;
    paused:play) next=playing action=resume ;;
    playing:stop | paused:stop) next=stopped action=rewind ;;
    *) next=$state action=ignored ;;
  esac
  echo "$event: $action ($state -> $next)"
  state=$next
}

for event in play pause play stop pause; do
  handle "$event"
done
Output
play: start at 0:00 (stopped -> playing)
pause: hold the position (playing -> paused)
play: resume (paused -> playing)
stop: rewind (playing -> stopped)
pause: ignored (stopped -> stopped)
  • Verdict: idiom. The shell has no objects, so the state is a string, and a case on the string "state:event" is the table. This is the enum and match form of the node page.
  • | joins two patterns in one arm, and * is the default arm.
  • A shell function can be a state too: the variable holds a function name, and "$state" "$event" calls it. The case form keeps the whole machine in one place.

Consequences

Design Patterns lists three consequences.1 The pattern puts the behaviour for one state in one class, and it separates the behaviour of different states. It makes the transitions explicit: a change of state is one assignment of the state object, so the context cannot be in a state between two states. And a state object with no fields can be shared by all contexts.

The costs are many small classes and coupling between them. Design Patterns says that the pattern increases the number of classes, and that this is good when there are many states.1 The Rust book names two downsides of its state objects. The states are coupled to each other, so a state added between two states changes the code of one of them. And some logic is duplicated across the states.4

Do not put the data of one context in a shared state object. The examples share one object for each state, as Design Patterns suggests for states without fields.1 A field on a shared state is shared by every context:

This code runs but gives a wrong answer on purpose.

class Playing:
    def __init__(self):
        self.position = 0

    def listen(self, seconds):
        self.position += seconds


PLAYING = Playing()  # one object for every player


class Player:
    def __init__(self, title):
        self.title = title
        self.state = PLAYING

    def listen(self, seconds):
        self.state.listen(seconds)


song, podcast = Player("song"), Player("podcast")
song.listen(20)
podcast.listen(15)
print(f"song at {song.state.position} s, podcast at {podcast.state.position} s")
Output
song at 35 s, podcast at 35 s

Each player should be at its own position. There are two fixes. Keep the position in the context and pass the context to the state. Or make a state object for each context when the state is entered. Design Patterns discusses the second choice as the question of when to create and destroy state objects.1

When not to use it

Do not use the pattern for two or three states with one line of code each. A field and a conditional are shorter, and the reader sees all of the behaviour in one place.

Do not use state classes when the transitions are the main thing to read and test. A table, or an enum with a match, shows the whole machine in one function. A test can call that function with a state and an event, and no context object.

Do not use state classes when a state machine is generated or loaded as data. Parsers and protocol engines often hold their machine as a table that a tool makes from a grammar or a specification.

Functions as states. A state can be a function that does the work and returns the next state. Norvig lists State among the six patterns that first-class types make invisible or less complex.2 The lexer of Go's text/template declares type stateFn func(*lexer) stateFn.6 Its loop is state = state(l), and it stops when a state returns nil.7 See Closure.

Enums with behaviour. In Java, an enum constant can have a class body that overrides the methods of the enum, so each constant is a state object.8 The Java example uses this.

Flyweight and Singleton. Design Patterns relates State to Flyweight, for sharing state objects, and notes that state objects are often singletons.1 See Singleton pattern. A module constant, an enum constant or a const global does this without a singleton class.

Strategy. The section above compares them. See Strategy pattern.

Command. A state machine often receives its events as command objects, and a command can be the action of a transition. See Command pattern.

Refactorings. Kerievsky's Replace State-Altering Conditionals with State moves the conditionals that change a state field into state classes.9 Fowler's Replace Conditional with Polymorphism is the general form.10

Known uses

  • Go: the template lexer in src/text/template/parse/lex.go at go1.27.3 holds each state as a function of type stateFn, and nextItem runs states until one returns nil.67
  • TCP: the connection of RFC 9293 is a state machine with eleven states, and it is the motivating example of Design Patterns.31

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, State (Intent, Also Known As, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
  2. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (State is one of the six patterns affected by first-class types)
  3. RFC 9293, Transmission Control Protocol (TCP), IETF, 2022, section 3.3.2, State Machine Overview
  4. The Rust Programming Language, chapter 18.3, Implementing an Object-Oriented Design Pattern, sections on the trait object design, its trade-offs, the note on enums, and encoding states and behaviour as types
  5. The Rust Programming Language, chapter 6.2, The match Control Flow Construct, Matches Are Exhaustive
  6. Go go1.27.3 source, src/text/template/parse/lex.go, type stateFn, lines 109 to 110
  7. Go go1.27.3 source, src/text/template/parse/lex.go, nextItem, lines 226 to 238
  8. The Java Language Specification, Java SE 25 Edition, 8.9.1 Enum Constants
  9. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 7, Simplification, Replace State-Altering Conditionals with State
  10. Martin Fowler, Refactoring catalog, Replace Conditional with Polymorphism, catalog entry

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M5W08S/text.yaml