Command
medium 50 minA 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
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
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.
1994
Thomas Berlage describes a selective undo mechanism for graphical user interfaces based on command objects in ACM TOCHI (September).
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.
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 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.
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)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
1/3A button knows a device
The remote calls the light by name.
uses
Callers run commands
- Callers know
executeand 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
1/4The contract
The invoker holds commands through an interface. It can run them and take them back.
has (lives on)implementsusesdepends on
Press, undo, redo
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
| Step | Light | Done, newest right | Undone, newest right |
|---|---|---|---|
| start | 0 | ||
| press full | 100 | full | |
| press half | 50 | full, half | |
| undo | 100 | full | half |
| undo | 0 | half, full | |
| redo | 100 | full | half |
| press off | 0 | full, off | emptied |
How does a command take itself back?
BreaksCall the opposite method
- How
undoof 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.
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)More uses
Queue, log, schedule, combine
| Because it is an object, you can | What the invoker does | Example |
|---|---|---|
| keep it | pushes it on a history | undo in an editor |
| delay it | puts it in a queue | print jobs, background workers |
| repeat it | runs it again after a failure | payment retries |
| record it | writes it down before running it | recovery after a crash, audit |
| send it | turns it into data | job on another machine |
| combine it | runs a list as one | macro, installation steps |
| exchange it | puts another one in the slot | key bindings of a game |
| ask it | calls canExecute | a grey menu entry |
A macro is a command
1/3One interface
The remote runs whatever is a command.
usesimplementshas (lives on)
Movie mode
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
| Form | Looks like | Can be undone | Can be stored |
|---|---|---|---|
| Function | lambda: light.set_level(50) | no | no |
| Object | SetLevel(light, 50) | yes, remembers before | only in memory |
| Data | {"kind": "set_level", "light": 7, "level": 50} | if the old value is stored too | yes |
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.