Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 57 ยท Behavioral Patterns

State

Learn the State design pattern: let an object change its behavior when its state changes. Compare state objects with enums using a vending machine and order workflow.

The State pattern lets an object behave differently depending on its current state, as if it changed its class at run time. Instead of one big class full of if (state === "idle") ... else if (state === "paying") ..., each state becomes its own small object that knows what to do, and which state comes next.

Many things have states: a traffic light, a network connection, a document (draft, in review, published), an order (placed, paid, shipped, delivered) and a vending machine. In each, the same action means different things at different times. Pressing "pay" on a shipped order is a mistake; pressing it on a placed order is how it moves forward. A state machine is the model behind this: a fixed set of states, events, and the allowed transitions between them.

One object, many behaviors

Context The object whose behavior changes.
State objects One small class per state.
Transitions A state decides what comes next.

The context forwards each action to its current state.

1 / 2

The structure

The context holds a reference to a current state object and delegates the work to it. Each state implements the same interface and may replace the context's state with another one.

stateDiagram-v2
    [*] --> Idle
    Idle --> HasMoney : insertCoin
    HasMoney --> HasMoney : insertCoin
    HasMoney --> Idle : refund
    HasMoney --> Dispensing : select
    Dispensing --> Idle : done

The vending machine used in this lesson. Every arrow is one allowed transition; anything not drawn is not allowed.

A vending machine with state objects

Each state class answers the same three questions: what happens on insertCoin, on select and on refund. States that do not allow an action say so. The machine itself has no if on the state at all.

JS A vending machine built from state objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Adding a state, such as OutOfService, means writing one new class and changing the transitions that lead to it. The existing states stay readable because each one only contains the rules for itself.

The simpler way: an enum and a transition table

State objects are not always worth it. When the states only differ in which transitions are allowed, and there is little behavior per state, a plain enum with a table is shorter, easier to read and easy to check by eye. This is how many order workflows are written. The table below says: in state X, event Y moves to state Z. Anything not in the table is rejected.

JS An order workflow as a transition table

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Since the rules are data, you can print them, draw a diagram from them, or test that every state is reachable and every non-final state has a way out.

Choosing between them

Situation Reach for
Few states, little per-state behavior Enum and switch, or a transition table
Each state has its own non-trivial logic and data State objects
States and transitions change often, or come from configuration Transition table or a state-machine library
Behavior depends on several independent flags Several small state machines, not one with every combination

Beware a state explosion: if you find yourself with states like PaidAndShippedAndGiftWrapped, you are modelling two independent things in one machine. Split them.

Common mistakes

  • Who owns transitions? If states decide their successors, the state classes know about each other. If the context decides, the states stay simple but the context grows. Pick one and be consistent.
  • Creating new state objects on every transition. States without data can be shared, for example as singletons or constants.
  • Forgetting invalid actions. Decide what happens when an action is not allowed: ignore it, report it, or throw an error. Silent failure hides bugs.
  • Mixing state with data. The state says where you are in the process; the context's fields (credit, stock) are the data that carry across states.

State and Strategy have almost the same class diagram, since both delegate to a replaceable object. The difference is intent. A strategy is chosen from outside and usually stays; states change themselves as the object runs, and know about one another. Because states are objects with shared behavior, you can also write common code in a base class, in the style of Template Method. And when each transition should be recorded or undone, combine State with Command.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the context do in the State pattern?

    The context forwards each action to its current state object. Changing the state object changes the behavior, with no conditionals in the context.
  2. 2. Which description best fits a state machine?

    A state machine is defined by its states, the events it reacts to, and which event moves it from which state to which.
  3. 3. When is an enum plus a transition table a better choice than state classes?

    A table is short, reviewable and inspectable. Use state objects when each state carries enough behavior to deserve its own class.
  4. 4. How is State different from Strategy, given that both delegate to a replaceable object?

    The structure is similar, but states represent where the object is in its life and trigger transitions; strategies are alternative ways to do the same job.
  5. 5. An order object has states like PaidAndShippedAndGiftWrapped. What is the likely design problem?

    When independent properties are multiplied into single states, the number of states grows fast. Model them as separate small machines or fields instead.

Summary

  • State lets an object change behavior when its internal state changes, without conditionals on the state in the context.
  • Each state is an object with the same interface; the context delegates to the current one.
  • An enum with a transition table is often simpler when states differ mostly in allowed transitions.
  • Decide who owns transitions, and decide what invalid actions do.
  • Avoid state explosion by splitting independent aspects into separate machines.
  • Structure is like Strategy; intent differs, because states move themselves.

Next lesson: Template Method.