Command Pattern — Design Patterns

The Command pattern wraps one action in an object (a command) with do() to run it and undo() to cancel it. Since it's an object, the action can be kept…

Ctrl+Z, a job queue that runs tonight, and a log of "who changed what" share one idea: the action is kept first. It isn't done right away and then lost.

The Command pattern wraps one action in an object, called a command. It holds how to run the action (do), how to cancel it (undo), and the data it needs. Since it's an object, the action can be kept in a history (a list of the actions that have run), so it can be undone. It can also be put in a queue (a list of actions waiting for their turn) to run later, or logged and replayed (run again). Picture the order slips at a food stall. The waiter writes the order on a slip instead of shouting it at the kitchen. Slips can be queued and cooked in order, crossed out when a customer cancels, and kept as a record at the end of the day. A shouted order is gone once it is heard. In code, the waiter is the code that receives the admin's click, one order slip is one command, and shouting at the kitchen is changing the data directly. The slips waiting to be cooked are the queue, crossing out a slip is undo, and the kept slips are the log.

The problem: buttons that change data directly

In the first admin panel, each button writes parcel.status = "delivered" right away. If the admin misclicks, the old status is overwritten and isn't kept anywhere, so there's nothing to undo. Running 300 status changes tonight, or recording who changed what, isn't possible either: the action happens at that moment and is gone.

Command: an action as an object

In this version, changeStatus makes a command that changes a status. run runs a command and keeps it in history, and undoLast cancels the last one:

const parcel = { trackingNo: "KCL-0001", status: "transit" }

function changeStatus(parcel, newStatus) {
  let oldStatus
  return {
    status: newStatus,
    do() {
      oldStatus = parcel.status // remembered when it runs
      parcel.status = newStatus
    },
    undo() {
      parcel.status = oldStatus
    },
  }
}

const history = []

function run(cmd) {
  cmd.do()
  history.push(cmd)
}

function undoLast() {
  const cmd = history.pop()
  if (!cmd) return false
  cmd.undo()
  return true
}

run(changeStatus(parcel, "delivering"))
run(changeStatus(parcel, "delivered"))
console.log(parcel.status) // delivered
undoLast()
console.log(parcel.status) // delivering
undoLast()
console.log(parcel.status) // transit
console.log(undoLast())    // false
step history parcel.status
start empty transit
run(changeStatus(parcel, "delivering")) delivering delivering
run(changeStatus(parcel, "delivered")) delivering, delivered delivered
undoLast() delivering delivering
undoLast() empty transit
undoLast() empty, returns false transit

Undo must remember, not guess

An undo that keeps nothing has to guess. Here is one that steps back one place in the status list:

const STATUS = ["picked_up", "transit", "delivering", "delivered"]

undo() {
  parcel.status = STATUS[STATUS.indexOf(parcel.status) - 1] // one step back
}

The admin changes KCL-0001 from transit straight to delivered (the courier forgot to scan delivering), then presses undo. Take a guess first: what status does the parcel end up with?

The guessing undo steps back one place from delivered, so it gives delivering: a status this parcel never had. The right undo returns transit, because do() already kept it.

When the old status is kept matters too. Keep it inside do(), not when the command is created. Otherwise, a command created at 9 and run at 12 would remember the status at 9, which may have changed since.

Queues and replay: commands as data

A command can be made now and run later. If queue holds 300 status-change commands, queue.forEach(run) runs them all at night, one at a time. A command written as plain data can be saved as JSON and replayed somewhere else. Here log holds two commands written as data:

const log = [
  { type: "changeStatus", trackingNo: "KCL-0001", status: "delivering" },
  { type: "changeStatus", trackingNo: "KCL-0001", status: "delivered" },
]

// say, data restored from this morning's backup
const restored = { "KCL-0001": { trackingNo: "KCL-0001", status: "transit" } }
for (const c of log) run(changeStatus(restored[c.trackingNo], c.status))
console.log(restored["KCL-0001"].status) // delivered

The for loop makes a command again from each entry in log, then runs it on restored. Replaying the same log on the same starting state gives the same final state. Libraries and frameworks often use this pattern:

A CSS selector isn't a command: it's a style declaration, not an action that can be run, queued or undone.

Exercise: createCommandStack

In the exercise, you write an undo history that works for any command. The starter (the code already in the editor) has counter, two commands (counter += 5 and counter *= 2, each with its opposite) and three console.log calls. You write createCommandStack(), which returns an object with:

How it runs: counter starts at 0. 0 + 5 = 5, then 5 × 2 = 10, so the first line printed is 10. Two undos take from the top of the stack: 10 / 2 = 5, then 5 - 5 = 0, so the second line is 0. A third undo on an empty history prints false. Also graded: one +5 command runs twice, then is undone once. The result must be 10|2|true|5: the number after two runs, size(), what undo() returns, and the number after the undo.

When you don't need a command

⚠️ Why does undo cancel the wrong thing?

TL;DR: The Command pattern wraps one action in an object (a command) with do() to run it and undo() to cancel it. Since it's an object, the action can be kept, queued, undone or replayed. An undo history is a stack: the last one in is the first one out. In the exercise, execute calls cmd.do() then pushes it onto the history, and undo takes the last command with pop, calls cmd.undo(), and returns true, or false when the history is empty. Undo must remember the old state kept in do(), not guess it. A parcel changed straight from transit to delivered, then undone by guessing (one step back in the status list), ends up at delivering, a status it never had. Commands as data ({ type, trackingNo, status }) can be queued and replayed. Libraries and frameworks do this: Redux actions, Laravel Jobs, BullMQ. A one-off action with no undo is just called directly.

⚡ An action as an object

Write:

function changeStatus(parcel, newStatus) {
  let oldStatus
  return {
    status: newStatus,
    do() {
      oldStatus = parcel.status // remembered when it runs
      parcel.status = newStatus
    },
    undo() {
      parcel.status = oldStatus
    },
  }
}

Meaning: The Command pattern wraps one action in an object (a command) with do() to run it and undo() to cancel it, so the action can be kept, queued or undone. Calling changeStatus doesn't change anything yet. do() makes the change, after keeping the current status in oldStatus for undo().

⚡ The history is a stack

Meaning: The history is an array of the commands that have run, and it's used as a stack: the last one in is the first one out. run(cmd) calls cmd.do(), then puts that command on top of the history with push. undoLast() takes the last command (cmd) with pop, calls cmd.undo(), and returns true, or false when the history is empty.

⚡ Undo must remember, not guess

Guess first: the admin changes KCL-0001 from transit straight to delivered, then presses a guessing undo. This undo keeps no old status, so it steps back one place in the status list (picked_up, transit, delivering, delivered). What status does it end up with?

delivering: a status this parcel never had. The right undo returns transit, because do() already kept it.

Meaning: Keep the old status inside do(), not when the command is created. Otherwise, a command created at 9 and run at 12 would remember the status at 9, which may have changed since.

What you will learn