State Pattern — Design Patterns

The State pattern gives each condition (a state) one object that holds all its rules. For a Kancil Courier parcel, each status has an object with allowed (the…

Why does the "open" button on a car park barrier sometimes do nothing? Because the barrier has a state. While it waits for a ticket, the button does nothing. Once the ticket is paid, the same button lifts the barrier. While the barrier is up, inserting another ticket is refused. And the barrier can't jump from "waiting for a ticket" straight to "open".

The State pattern puts every rule of one condition (a state) in one object: which actions are allowed, which states may come next, and what happens when an action runs. The main object only forwards each action to the state object that is active, so its behaviour changes when its state does. In the car park picture, the barrier is the main object, each condition of the barrier is one state object, and the "open" button is an action. A move from one state to another is called a transition. The set of states and their valid transitions is called a state machine, and the rule against jumping to "open" is one of its rules.

The problem: the status is read in four functions

At Kancil Courier, a parcel's state is its status. There are four statuses: picked_up, transit, delivering, delivered. The first version reads the status in four functions. Three functions have their own switch, and changeStatus checks nothing:

function changeStatus(p, next) {
  p.status = next // no check at all
  return "SMS: " + smsMessage(p)
}
function smsMessage(p) {
  switch (p.status) {
    case "picked_up": return p.trackingNo + " picked up by the courier"
    case "transit": return p.trackingNo + " arrived at the transit warehouse"
    case "delivering": return p.trackingNo + " out for delivery"
    case "delivered": return p.trackingNo + " received"
  }
}
function progress(p) {
  switch (p.status) {
    case "picked_up": return 25
    case "transit": return 50
    case "delivering": return 75
    case "delivered": return 100
  }
}
function changeAddress(p, address) {
  switch (p.status) {
    case "picked_up":
    case "transit":
      p.address = address
      return "address changed: " + address
    default:
      return "refused: the courier has left"
  }
}

A new status returned (the parcel goes back to the sender) means changing all three switch blocks. If you miss one, say in smsMessage, the customer gets SMS: undefined, with no error.

State objects: each status knows its own rules

In the State pattern version, each status has its own object in STATES. createParcel makes a parcel object that forwards its actions to the active state object:

const STATES = {
  picked_up: {
    allowed: ["transit"],
    progress: 25,
    sms: (trackingNo) => trackingNo + " picked up by the courier",
    changeAddress: (p, address) => { p.address = address; return "address changed: " + address },
  },
  transit: {
    allowed: ["delivering"],
    progress: 50,
    sms: (trackingNo) => trackingNo + " arrived at the transit warehouse",
    changeAddress: (p, address) => { p.address = address; return "address changed: " + address },
  },
  delivering: {
    allowed: ["delivered", "transit"], // failed delivery: back to the warehouse
    progress: 75,
    sms: (trackingNo) => trackingNo + " out for delivery",
    changeAddress: () => "refused: the courier has left",
  },
  delivered: {
    allowed: [], // end of the journey
    progress: 100,
    sms: (trackingNo) => trackingNo + " received",
    changeAddress: () => "refused: the parcel was already delivered",
  },
}

function createParcel(trackingNo) {
  let status = "picked_up"
  return {
    trackingNo,
    address: "5 Jasmine Street",
    getStatus: () => status,
    getProgress: () => STATES[status].progress,
    changeStatus(next) {
      if (!STATES[status].allowed.includes(next)) return "refused: " + status + " → " + next
      status = next
      return "SMS: " + STATES[status].sms(trackingNo)
    },
    changeAddress(address) {
      return STATES[status].changeAddress(this, address)
    },
  }
}

Allowed transitions, and refused ones

Here is one parcel that tries several transitions. The result of each line is in its comment:

const p = createParcel("KCL-0001")
console.log(p.changeAddress("9 Maple Street")) // address changed: 9 Maple Street
console.log(p.changeStatus("transit"))         // SMS: KCL-0001 arrived at the transit warehouse
console.log(p.changeStatus("delivered"))       // refused: transit → delivered
console.log(p.changeStatus("delivering"))      // SMS: KCL-0001 out for delivery
console.log(p.changeAddress("2 Cedar Street")) // refused: the courier has left
console.log(p.changeStatus("delivered"))       // SMS: KCL-0001 received
console.log(p.changeStatus("picked_up"))       // refused: delivered → picked_up

Four of those results, in short:

status before action result status after
picked_up changeStatus("transit") SMS sent transit
transit changeStatus("delivered") refused, delivering skipped transit
delivering changeAddress(...) refused, the courier has left delivering
delivered changeStatus("picked_up") refused, the journey is over delivered

The old version accepts everything. Say KCL-0001 is already delivered, and then the courier scans it as picked_up by mistake. The old changeStatus(p, "picked_up") only writes p.status = next. The customer gets SMS: KCL-0001 picked up by the courier, and the tracking page drops back to 25% progress. The state machine refuses it with refused: delivered → picked_up, and no SMS. The jump from transit to delivered in the Command Pattern lesson is refused now too.

State or Strategy?

Both look alike: an object full of functions, and main code that forwards the call to one of them. The difference is who switches it:

Exercise: a vending machine

In the exercise, you use the same shape for a drinks machine (a vending machine). createMachine(stock) returns { insertCoin, selectProduct, getState }: insert a coin, pick a drink, and read the state's name. The machine has three states:

state insertCoin() selectProduct()
"NoMoney" move to "HasMoney", return "coin accepted" "insert coin first"
"HasMoney" "coin already inserted" lower the stock, move to "SoldOut" if it reaches 0 or "NoMoney" if some is left, return "dispensed"
"SoldOut" "machine sold out" "machine sold out"

It starts in "NoMoney" when the stock is more than 0, and in "SoldOut" when it's 0. For createMachine(1), the console prints insert coin first, coin accepted, dispensed, then SoldOut from getState(). With a stock of 2, the order select (selectProduct), coin (insertCoin), select, coin, select gives insert coin first, coin accepted, dispensed, coin accepted, dispensed, and the final state is SoldOut.

When to use it, when not to

⚠️ Statuses that escape the machine

TL;DR: The State pattern gives each condition (a state) one object that holds all its rules. For a Kancil Courier parcel, each status has an object with allowed (the valid next statuses), progress, sms and changeAddress. The parcel object forwards each action to the active state object. So the old version's switch, spread over four functions, goes away, and a new status is one object. allowed enforces valid transitions (moves between statuses): delivered → picked_up is refused, where the old version sent a "picked up" SMS and dropped the progress to 25%. Strategy is picked from outside by the caller, while State switches by itself as a result of an action. In the exercise, the drinks machine has the states NoMoney, HasMoney and SoldOut, which each answer insertCoin and selectProduct with their own message, and getState() returns the state's name. For two simple conditions, a boolean is enough.

⚡ Each status knows its own rules

Write:

  delivering: {
    allowed: ["delivered", "transit"], // failed delivery: back to the warehouse
    progress: 75,
    sms: (trackingNo) => trackingNo + " out for delivery",
    changeAddress: () => "refused: the courier has left",
  },

Meaning: The State pattern puts every rule of one condition (a state) in one object. This is the object for the delivering status: allowed holds the valid next statuses, progress the number on the tracking page, sms the message for the customer, and changeAddress its reaction when someone asks to change the address. The old version read the status with a switch in four functions. With one object per status, that switch goes away, and a new status is one object.

⚡ The same method, behaviour that follows the status

Write:

    changeAddress(address) {
      return STATES[status].changeAddress(this, address)
    },
Guess first: STATES holds one object per status, and status keeps the parcel's current status. This parcel object only moves to a status listed in allowed, and delivered has an empty allowed list. The old version writes any new status without checking. KCL-0001 is already delivered, then the courier scans it as picked_up by mistake. What happens in the old version, and in this parcel object?

The old version sends SMS: KCL-0001 picked up by the courier, and the progress drops back to 25%. This parcel object refuses it, because delivered has an empty allowed list.

Meaning: The parcel object only forwards each action to the active state object, so its behaviour changes with its status. The same changeAddress changes the address while the parcel is picked_up, and refuses while it is delivering.

⚡ State or Strategy?

Meaning: The code looks alike: an object full of functions. Strategy is picked from outside by the caller, for example a promo passed to the checkout. State switches by itself as a result of an action inside the object, for example changeStatus("delivering"), which makes changeAddress start refusing. For two simple conditions, a boolean is enough.

What you will learn