Skip to content

State Pattern: Explicit State Machines Without the Switch Statements

Learn the State pattern by refactoring an EV charger's switch-heavy firmware into state objects that own their behaviour and transitions.

13 min readDesign patternBehavioural

Let an object change its behaviour when its internal state changes, by moving each state's behaviour into a separate class and delegating to the current one. From the outside it looks as if the object changed its class.

Some objects behave differently depending on what has already happened to them. A charger that is mid-session should not accept a new card. A faulted charger should not deliver power, whatever button gets pressed. The usual first version of this logic is a status field and a switch statement in every method. It works until the fifth state arrives. The State pattern turns each state into its own object. The owner delegates every call to whichever state object is current, and that object decides what to do and which state comes next. In this guide you will follow one charging network from a tangle of conditionals to an explicit state machine, then see how to explain the trade-offs in an interview.

The problem

A situation where the obvious design starts to hurt.

VoltBay runs 420 public EV chargers across 60 car parks. A team of four writes the firmware that sits between the hardware and the central backend. Every charger is modelled by a ChargePoint class with a status string that can be available, authorized, charging or faulted.

The class has five event methods: tapCard, plugIn, unplug, fault and reset. Each one opens with a switch on status, so there are five switches of four branches each, twenty branches to keep consistent. When the product team asked for a reserved state, so drivers could book a bay from the app, the change touched every switch plus three helper methods that also checked status.

Then a field bug arrived: a charger in faulted state started delivering power because the plugIn switch had a fall-through that nobody had noticed. The rule "a faulted charger never powers on" was not written anywhere. It was implied by the absence of code across five methods. Reviewers could not see the state machine because it was smeared across the whole class.

The solution

What the pattern proposes.

Give each state its own class. Available, Authorized, Charging and Faulted all extend an abstract ChargerState that declares the five events. The base class supplies safe defaults: every event is rejected, except fault, which always cuts power and moves to Faulted. Each concrete state overrides only the events it actually handles.

ChargePoint becomes the context. It holds a reference to the current state object, exposes hardware operations such as startPower and stopPower, and forwards each event to the state with itself as an argument. The state does its work and, if needed, calls cp.setState(...) to install the next state.

Now the rule about faulted chargers lives in one place: Faulted does not override plugIn, so it inherits the rejection. Adding Reserved means writing one new class and changing the one or two states that can transition into it. Each state class reads like a row of the state transition table, which is exactly what a reviewer needs to see.

An everyday analogy

The same idea, outside software.

Think of a self-service car wash bay. When it is idle, the coin slot accepts money and the start button does nothing. Once you have paid, the start button begins the wash and the coin slot is closed. While the brushes are running, the only control that matters is the emergency stop. If a sensor trips, every control is dead until an attendant turns the key.

The buttons on the panel never change. What changes is the mode the machine is in, and each mode decides what the same buttons mean and which mode follows. The State pattern gives each of those modes its own object instead of wiring every button to a long list of checks.

Structure

The pieces and how they relate.

ChargePoint delegates every event to its current ChargerState; concrete states perform the work and install the next state.OcppHandler calls ChargePoint (events). ChargePoint has a ChargerState (current state). Available inherits from ChargerState. Authorized inherits from ChargerState. Charging inherits from ChargerState. Faulted inherits from ChargerState. Available creates Authorized (tapCard). Authorized creates Charging (plugIn). ChargerState creates Faulted (fault). Charging calls ChargePoint (stopPower, setState).OcppHandlersends hardware andbackend eventsChargePointcontext: holdsstate, power control«abstract»ChargerStatetapCard, plugIn,unplug, fault, resetAvailableaccepts a cardAuthorizedholds cardId, waitsfor plugChargingpower on untilunplugFaultedrejects all butresetTransitionsstates callcp.setState(next)eventscurrent statetapCardplugInfaultstopPower, setState
ChargePoint delegates every event to its current ChargerState; concrete states perform the work and install the next state.

Participants

ChargePoint (Context)
Owns the current state object and the real resources, here the power relay. Exposes the public event methods and forwards each one to the current state, passing itself so the state can act on it and replace itself.
ChargerState (State)
Abstract base declaring every event the context can receive. Provides default behaviour: reject the event, except fault, which cuts power and moves to Faulted from any state.
Available, Authorized, Charging, Faulted (Concrete States)
Each implements the behaviour valid in that state and decides the next state. They may carry state-specific data, such as the card that authorised the session.
OcppHandler (Client)
Translates hardware signals and backend messages into calls on ChargePoint. It never inspects or changes the state directly.

Pseudocode

The solution to the scenario, language-neutral.

abstract class ChargerState
  method tapCard(cp, cardId): return reject("tapCard")
  method plugIn(cp): return reject("plugIn")
  method unplug(cp): return reject("unplug")
  method reset(cp): return reject("reset")
  method fault(cp, code):
    cp.stopPower()
    cp.setState(new Faulted(code))

class Available extends ChargerState
  method tapCard(cp, cardId):
    cp.setState(new Authorized(cardId))

class Authorized extends ChargerState
  field cardId
  method tapCard(cp, otherCard):
    if otherCard == cardId then cp.setState(new Available())
    else reject: bay held for cardId
  method plugIn(cp):
    cp.startPower()
    cp.setState(new Charging(cardId))

class Charging extends ChargerState
  field cardId
  method unplug(cp):
    cp.stopPower()
    cp.setState(new Available())

class Faulted extends ChargerState
  field code
  method reset(cp): cp.setState(new Available())

class ChargePoint
  field state = new Available()
  method setState(next): state = next
  method tapCard(cardId): return state.tapCard(this, cardId)
  method plugIn(): return state.plugIn(this)
  // unplug, fault, reset forward the same way

The code

The same solution in TypeScript, Python and PHP.

abstract class ChargerState {
  abstract name(): string;

  tapCard(_cp: ChargePoint, _cardId: string): string {
    return this.reject("tapCard");
  }

  plugIn(_cp: ChargePoint): string {
    return this.reject("plugIn");
  }

  unplug(_cp: ChargePoint): string {
    return this.reject("unplug");
  }

  reset(_cp: ChargePoint): string {
    return this.reject("reset");
  }

  fault(cp: ChargePoint, code: string): string {
    cp.stopPower();
    cp.setState(new Faulted(code));
    return `fault ${code}: power cut`;
  }

  protected reject(action: string): string {
    return `${action} ignored while ${this.name()}`;
  }
}

class Available extends ChargerState {
  name(): string {
    return "available";
  }

  tapCard(cp: ChargePoint, cardId: string): string {
    cp.setState(new Authorized(cardId));
    return `card ${cardId} authorized, plug in to start`;
  }
}

class Authorized extends ChargerState {
  constructor(private readonly cardId: string) {
    super();
  }

  name(): string {
    return "authorized";
  }

  tapCard(cp: ChargePoint, cardId: string): string {
    if (cardId === this.cardId) {
      cp.setState(new Available());
      return `authorization for ${cardId} cancelled`;
    }
    return `card ${cardId} rejected: bay held for ${this.cardId}`;
  }

  plugIn(cp: ChargePoint): string {
    cp.startPower();
    cp.setState(new Charging(this.cardId));
    return `charging for card ${this.cardId}`;
  }
}

class Charging extends ChargerState {
  constructor(private readonly cardId: string) {
    super();
  }

  name(): string {
    return "charging";
  }

  unplug(cp: ChargePoint): string {
    cp.stopPower();
    cp.setState(new Available());
    return `session for ${this.cardId} closed`;
  }
}

class Faulted extends ChargerState {
  constructor(private readonly code: string) {
    super();
  }

  name(): string {
    return "faulted";
  }

  reset(cp: ChargePoint): string {
    cp.setState(new Available());
    return `fault ${this.code} cleared`;
  }
}

class ChargePoint {
  private state: ChargerState = new Available();
  powerOn = false;

  constructor(readonly id: string) {}

  setState(next: ChargerState): void {
    this.state = next;
  }

  stateName(): string {
    return this.state.name();
  }

  startPower(): void {
    this.powerOn = true;
  }

  stopPower(): void {
    this.powerOn = false;
  }

  tapCard(cardId: string): string {
    return this.state.tapCard(this, cardId);
  }

  plugIn(): string {
    return this.state.plugIn(this);
  }

  unplug(): string {
    return this.state.unplug(this);
  }

  fault(code: string): string {
    return this.state.fault(this, code);
  }

  reset(): string {
    return this.state.reset(this);
  }
}

const cp = new ChargePoint("VB-017");
const steps: Array<() => string> = [
  () => cp.plugIn(),
  () => cp.tapCard("C-881"),
  () => cp.tapCard("C-204"),
  () => cp.plugIn(),
  () => cp.fault("GROUND_FAULT"),
  () => cp.unplug(),
  () => cp.reset(),
];

for (const step of steps) {
  const result = step();
  console.log(`${result} -> ${cp.stateName()} (power ${cp.powerOn ? "on" : "off"})`);
}

When to use it

Situations where it pays off.

  • An object's behaviour depends on its state, and the same few conditionals on a status field appear in many methods.

    Each switch is a slice of the state machine. Moving the branches into state classes collects every rule for one state in one place, so adding or changing a state stops being shotgun surgery.

  • Some events are only legal in certain states and an illegal one must be harmless, such as powering on a faulted charger.

    A base class that rejects by default makes forbidden transitions the safe outcome. A state must opt in to an event by overriding it, rather than every method having to remember to opt out.

  • States carry their own data, like the card that authorised a session or the fault code that stopped it.

    State objects can hold fields that only make sense while that state is active. You avoid nullable fields on the context that are valid only some of the time.

  • Not when there are two states and one or two methods care about them.

    A boolean and an if statement are easier to read than an abstract class and two subclasses. Reach for the pattern when the number of states or state-dependent methods starts to grow.

How to implement it

Steps to introduce it in existing code.

  1. List every state and every event, then write the transition table: for each pair, what happens and which state comes next. This table is your specification and your test plan.

  2. Declare an abstract state class or interface with one method per event. Each method takes the context as a parameter so the state can call back into it.

  3. Put safe defaults in the base class, usually rejecting the event. Put transitions that apply to every state there too, like fault moving to Faulted.

  4. Create one concrete class per state and override only the events that do something in that state. Move any data that belongs to a single state into that class as a field.

  5. Change the context to hold a reference to the current state, add a setState method, and make each public event method forward to the state.

  6. Delete the old status field and switches. If other code needs to read the state for display or persistence, expose a name() on the state rather than leaking the object.

  7. Test each state in isolation by constructing it, calling events on a context, and asserting on the resulting state and side effects.

Pros and cons

What you gain and what you pay.

Pros

  • All behaviour for one state lives in one class, so the state machine is visible in the code rather than implied by scattered branches.
  • Adding a state means adding a class and touching only the states that transition into it, which keeps changes local (Open/Closed in practice).
  • Illegal events fall through to a shared default, which makes the safe behaviour automatic instead of something each method must remember.
  • State-specific data lives on the state object, so the context has no fields that are meaningful only part of the time.
  • Each state can be unit-tested on its own with a small fake or real context.

Cons

  • More classes. For a machine with two or three states and simple rules, the pattern adds structure that a single switch would not need.
  • Transitions are spread across state classes, so you cannot see the whole graph in one file. Keep the transition table in documentation or tests.
  • States that call back into the context create a two-way dependency, and the context often has to expose methods like startPower that only states should use.
  • Creating a new state object on every transition allocates; if states have no data, share single instances instead.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between State and Strategy?

The class diagrams are nearly identical: a context delegating to an interchangeable object. The difference is who swaps the object and why. With Strategy, the client picks an algorithm and it usually stays put; strategies do not know about each other. With State, the state objects replace themselves in response to events, so each state knows which states can follow it. If the swap is driven by the object's own history, you are looking at State.

Should the context or the state classes decide the next state?

Either works. Letting states call setState, as in the VoltBay code, keeps each transition next to the behaviour that causes it and makes adding states local. Centralising transitions in the context or a table gives you one place to read the whole graph, at the cost of the context knowing every state. In an interview, name both options and say which trade-off fits the problem.

When is a transition table better than the State pattern?

When states differ only in which transitions are allowed and carry little behaviour, a table mapping (state, event) to next state is shorter and easy to load from configuration. The State pattern earns its keep when each state has real logic, side effects such as switching power, or its own data. Many systems combine them: a table for legality, state classes for behaviour.

How do you persist a state machine to a database?

Store the state's name plus any state-specific data, for example authorized and the card id. On load, a small factory maps the name back to a state class and constructs it with the saved data. Do not serialise the state objects directly; the name is a stable contract, the class layout is not.

Do I need a new state object on every transition?

Only for states that hold data. Stateless states such as Available can be single shared instances, which avoids allocation and makes identity comparisons cheap. States like Authorized, which remember a card id, must be created per transition or the data would leak between chargers.

Next guide8 of 10 · Behavioral patternsStrategy: swap the rule without touching who uses itRead the next one