AlgoViz

Command

medium 50 min

A command wraps a request in an object: what to do, with which receiver and parameters.

Chapter mnemonic

Four Command pattern roles

Diner writes the ticket. Waiter rings it in. Chef cooks.

The waiter rings in an order and the chef cooks it. Who invokes and who receives?

The waiter invokes the command. The chef is the receiver that performs the work.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:52

Command

1:03Reel

Theory

Read or listen first. About 1 min.

What it is

Command is a behavioral design pattern. A request becomes an object with one main method, execute, and often a second one, undo.

The invoker triggers commands and may keep them. The receiver does the work. The command connects the two, so that they need not know each other.

A command is complete when it is made: whoever runs it later needs no further information.

Why it exists

It separates when from what. A button, a menu, a key, a timer and a network worker can trigger the same wish.

It gives a request a life of its own: it can wait, be repeated, be recorded, be refused, be taken back.

New actions are new classes. Invokers do not change.

A short history

  1. 1985

    Henry Lieberman publishes There's more to menu systems than meets the screen at SIGGRAPH, on treating menu operations as things of their own.

  2. 1994

    Thomas Berlage describes a selective undo mechanism for graphical user interfaces based on command objects in ACM TOCHI (September).

  3. 1994

    Design Patterns by Gamma, Helm, Johnson and Vlissides is published on 31 October and contains Command.

Words to know

Invoker
Runs commands and may keep them. It knows only the interface.
Receiver
The object that does the real work.
Macro
A command made of commands, with one undo.
Redo stack
Undone commands that can be run again until a new command arrives.
Idempotent
Running it twice has the same effect as once.
Compensation
A new action that makes up for one that cannot be undone.
Write-ahead log
Commands are written to disk before they are run, and replayed after a crash.
Merging
Joining neighbouring commands into one undo step. Also called compression.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Client makes a command. Receiver and parameters are put in

Understand it

Start here

A wish you can hold in your hand

A method call happens and is gone. You cannot keep it, send it, repeat it tomorrow or take it back. The pattern on this page turns a call into an object. The object remembers what to do, and to whom. Then it can wait, travel, and be done backwards.

The toy crane and its punched cards
12345readerGRABRIGHT 3DROPdoneundonebin

The crane never knew about cards. The card reader never knew about blocks. The card knows both, and that is all it knows.

Five parts

  • Command

    The interface: execute() and, if wanted, undo(). Other names: action, task, job, request.

  • Concrete command

    One wish with its receiver and parameters: SetLevel(light, 50), Paste, Save, Purchase.

  • Invoker

    Runs commands and keeps them: a remote, a menu item, a toolbar, a worker. It knows only the interface.

  • Receiver

    Does the real work: Light, Document, Account. It does not know that commands exist.

  • Client

    Makes the commands, gives each its receiver, and hands them to the invoker. The only part that knows all classes.

A restaurant works the same way. The guest writes a wish on a slip (command). The waiter collects and delivers slips and cannot cook (invoker). The cook reads them and cooks (receiver). A slip can wait in a row, be counted in the evening, and be cancelled, as long as nobody has started cooking.

Why

What goes wrong without it

A toolbar button calls the document directly. Then the menu and a keyboard shortcut need the same action, and then users want undo.

Python
class Light:    def __init__(self):        self.level = 30class Remote:    def __init__(self, light):        self.light = light        self.last = None    def press(self, button):        if button == "on":            self.light.level = 100        elif button == "off":            self.light.level = 0        elif button == "dim":            self.light.level = 50        self.last = button    def undo(self):        if self.last == "on":            self.light.level = 0        # the opposite of on?        elif self.last == "off":            self.light.level = 100      # was it really 100?        # dim: nobody knowslight = Light()remote = Remote(light)remote.press("on")remote.undo()print("was 30, is now", light.level)
Run it. Undo guesses the opposite of the last action. The light was at 30, it was set to 100, and undo switches it off.
Edit and run it in your browser

Two things are missing. The remote knows every device, so each new device edits it. And the past is not kept anywhere, so undo has to guess.

The design that hurts

Remote- last: String+ press(b): 7 ifs+ undo(): 7 ifsLight+ setLevel(n)

1/3A button knows a device

The remote calls the light by name.

uses

Three callers times three devices. With commands it is three callers, one interface, and three small classes.

Callers run commands

  • Callers know execute and nothing else
  • Each command keeps what its undo needs
  • Commands wait, travel and are stored
  • A caller is tested with a fake command

Callers call receivers

  • Every caller knows every device
  • Undo has to guess
  • Nothing can be queued, logged or repeated
  • A caller cannot be tested without devices

The idea

Put the call into an object

The pattern in general

historyInvoker- history: Command[]+ run(c)+ undo()«interface»Command+ execute()+ undo()

1/4The contract

The invoker holds commands through an interface. It can run them and take them back.

has (lives on)implementsusesdepends on

There is no arrow from the invoker to the receiver. That missing arrow is the pattern.

Press, undo, redo

The command asks for the old level before it writes the new one. That question is what makes undo exact.

Undo

Two stacks and one rule

Done commands lie on one stack, undone commands on another. Undo moves a command from the first to the second, redo moves it back. The rule: a new command empties the second stack.

Where a command lives

A history by hand

StepLightDone, newest rightUndone, newest right
start0
press full100full
press half50full, half
undo100fullhalf
undo0half, full
redo100fullhalf
press off0full, offemptied
Without the last row, redo would now run half after off: a state the user never saw.

How does a command take itself back?

BreaksCall the opposite method
How
undo of on is off.
Limit
Wrong if it was on already, or dimmed to 30. The opposite of an action is not always its undo.
Choose when
Only for true inverses, such as move by +3 and by -3.
WorksCopy the whole receiver before
How
A snapshot, as in Memento.
Limit
Memory, and it also takes back what others changed meanwhile.
Choose when
The change is too complex to describe.
StrongKeep exactly what you overwrite
How
before = light.level, read inside execute.
Limit
Each command must know what it touches, side effects included.
Choose when
The default.
Python
class Light:    level = 0class SetLevel:    def __init__(self, light, level):        self.light, self.level, self.before = light, level, None    def execute(self):        self.before, self.light.level = self.light.level, self.level    def undo(self):        self.light.level = self.beforelight, history = Light(), []button = SetLevel(light, 50)            # one object for every pressfor _ in range(2):    button.execute()    history.append(button)while history:    history.pop().undo()print("shared object, after 2 undos:", light.level)light.level = 0make = lambda: SetLevel(light, 50)      # a new object for each pressfor _ in range(2):    c = make()    c.execute()    history.append(c)while history:    history.pop().undo()print("new object each, after 2 undos:", light.level)
Run it. One command object in a button, pressed twice. The second press overwrites the memory of the first.
Edit and run it in your browser

More uses

Queue, log, schedule, combine

Because it is an object, you canWhat the invoker doesExample
keep itpushes it on a historyundo in an editor
delay itputs it in a queueprint jobs, background workers
repeat itruns it again after a failurepayment retries
record itwrites it down before running itrecovery after a crash, audit
send itturns it into datajob on another machine
combine itruns a list as onemacro, installation steps
exchange itputs another one in the slotkey bindings of a game
ask itcalls canExecutea grey menu entry

A macro is a command

Remote+ run(c)«interface»Command+ execute()+ undo()

1/3One interface

The remote runs whatever is a command.

usesimplementshas (lives on)

Good Night: light to 0, thermostat to 18. One press, one entry in the history, one undo.

Movie mode

Forwards light, TV, sound. Backwards sound, TV, light.

Functions

Do I need a class?

In languages with functions as values, a command without undo is simply a function: Runnable in Java, a closure in Python or TypeScript. A class earns its place when a command needs a second operation (undo, describe, cost), when it must be stored as data, or when it has to be compared and tested.

Function, object or data?

Three forms of one wish

FormLooks likeCan be undoneCan be stored
Functionlambda: light.set_level(50)nono
ObjectSetLevel(light, 50)yes, remembers beforeonly in memory
Data{"kind": "set_level", "light": 7, "level": 50}if the old value is stored tooyes

Choosing

When to use it and when not

Use it when

  • Users need undo and redo
  • Work is queued, scheduled or retried
  • Every change must be recorded
  • Several actions form one step
  • Buttons, menus and keys are configurable

Leave it when

  • A direct call does the job
  • There is no undo, no queue and no log
  • A function is enough
  • The action runs once at start
  • Dozens of one-line classes would hide the code

The price

  • Many small classes

    One for each action. Group them by receiver, or use functions for those without memory.

  • History costs memory

    Deleted text and old pictures stay alive. Set a limit, in bytes and not only in entries.

  • Undo is hard

    Side effects, other users, and the outside world. A sent e-mail cannot be unsent.

  • One step more to read

    From the button you see execute, not what happens. Good names carry the design.

Summary

The whole topic in one minute.

A command holds receiver, action and parameters. The invoker runs and keeps commands, the receiver knows nothing about them. Slots hold recipes, so that each press has its own object and its own memory.

Undo restores what execute overwrote. Two stacks, or one list with a position, and a new command drops the redo part. Macros undo backwards and take back finished parts when one fails.

Outside the process a command is data: id, kind, arguments, version. It may come twice and late, so effects are stored with ids. Parts that cannot be undone come last. Undo among several users is a new, checked command.

  • A command is a request as an object: receiver, action, parameters.
  • The invoker knows only the interface. The receiver knows nothing of commands.
  • Undo restores what was overwritten. It does not call the opposite.
  • Two stacks. A new command clears the redo stack.
  • Slots hold recipes, the history holds objects.
  • A macro undoes backwards, and cleans up if it fails in the middle.
  • To survive a restart, a command must be data with an id.

Sources