Command: An Action You Can Hold
When the dispatcher's plan for the morning is stored as rows of text and run by a switch on each action's name, every new kind of action means editing the runner; the Command pattern turns "Assign package 42 to Dana" into an object that can be stored, queued, logged and run later.
Journeyman · OOP · Updated
After this lesson you can
- Turn an action into an object that can be stored, queued, logged and run later
- Spot the smells that point to Command: a switch on an action's name, and actions that leave no trace
Key takeaways
- The smell: actions stored as rows of data and run by a switch on the action's name, with the log line typed again in each case.
- The cause: an action is a method call, which happens and is gone; there's nothing to hold, so it's faked with data.
- The fix: each action is an object that knows how to run itself and describe itself; the runner only calls them.
- A command can be a class, or a function with a label; once it needs undo, it needs to be more than one function.
Before this: Meet the Package Tracker, interfaces (a promise any class can keep), and passing a function as a value.
Every evening, Lakeside Parcel's dispatcher plans the next morning: which driver takes which package. "Assign package 42 to Dana. Assign package 43 to Leo." Then Dana calls: her van is full, so package 42 comes off her list. The plan runs at 8:00, when the drivers arrive, and every step is written to a log, so that when a customer asks where their package is, someone can see who moved it. A month from now the dispatcher wants an undo button. This lesson ends with a pattern called Command; first, how the plan works today.
The symptom: a switch on the action's name
The plan is a list of rows: the action's name, a package and a driver. At 8:00, a runner goes down the list and does each one:
DispatchBoard board = new DispatchBoard();
// Tonight's plan for the morning: rows of data, run at 8:00.
List<(string Action, int Package, string Driver)> plan = new List<(string, int, string)>
{
("assign", 42, "Dana"),
("assign", 43, "Leo"),
("unassign", 42, ""),
};
RunPlan(board, plan);
Console.WriteLine(board.Describe());
void RunPlan(DispatchBoard board, List<(string Action, int Package, string Driver)> plan)
{
foreach ((string action, int package, string driver) in plan)
{
switch (action)
{
case "assign":
board.Assign(package, driver);
Console.WriteLine( quot;Assign package {package} to {driver}");
break;
case "unassign":
board.Unassign(package);
Console.WriteLine( quot;Unassign package {package}");
break;
// Next month: "swap", and then an undo button.
}
}
}
class DispatchBoard
{
private readonly SortedDictionary<int, string> drivers = new SortedDictionary<int, string>();
public void Assign(int package, string driver) => drivers[package] = driver;
public void Unassign(int package) => drivers.Remove(package);
public string Describe() => "Board: " + string.Join(", ", drivers.Select(pair => quot;package {pair.Key} with {pair.Value}"));
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
record Step(String action, int pkg, String driver) { }
class DispatchBoard {
private final TreeMap<Integer, String> drivers = new TreeMap<>();
void assign(int pkg, String driver) { drivers.put(pkg, driver); }
void unassign(int pkg) { drivers.remove(pkg); }
String describe() {
List<String> lines = new ArrayList<>();
drivers.forEach((pkg, driver) -> lines.add("package " + pkg + " with " + driver));
return "Board: " + String.join(", ", lines);
}
}
void runPlan(DispatchBoard board, List<Step> plan) {
for (Step step : plan) {
switch (step.action()) {
case "assign" -> {
board.assign(step.pkg(), step.driver());
IO.println("Assign package " + step.pkg() + " to " + step.driver());
}
case "unassign" -> {
board.unassign(step.pkg());
IO.println("Unassign package " + step.pkg());
}
// Next month: "swap", and then an undo button.
default -> { }
}
}
}
void main() {
DispatchBoard board = new DispatchBoard();
// Tonight's plan for the morning: rows of data, run at 8:00.
List<Step> plan = List.of(new Step("assign", 42, "Dana"), new Step("assign", 43, "Leo"), new Step("unassign", 42, ""));
runPlan(board, plan);
IO.println(board.describe());
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard:
def __init__(self):
self.drivers = {}
def assign(self, package, driver):
self.drivers[package] = driver
def unassign(self, package):
del self.drivers[package]
def describe(self):
return "Board: " + ", ".join(f"package {p} with {self.drivers[p]}" for p in sorted(self.drivers))
def run_plan(board, plan):
for action, package, driver in plan:
match action:
case "assign":
board.assign(package, driver)
print(f"Assign package {package} to {driver}")
case "unassign":
board.unassign(package)
print(f"Unassign package {package}")
# Next month: "swap", and then an undo button.
board = DispatchBoard()
# Tonight's plan for the morning: rows of data, run at 8:00.
plan = [("assign", 42, "Dana"), ("assign", 43, "Leo"), ("unassign", 42, "")]
run_plan(board, plan)
print(board.describe())
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map();
assign(pkg, driver) { this.#drivers.set(pkg, driver); }
unassign(pkg) { this.#drivers.delete(pkg); }
describe() {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
function runPlan(board, plan) {
for (const [action, pkg, driver] of plan) {
switch (action) {
case "assign":
board.assign(pkg, driver);
console.log(`Assign package ${pkg} to ${driver}`);
break;
case "unassign":
board.unassign(pkg);
console.log(`Unassign package ${pkg}`);
break;
// Next month: "swap", and then an undo button.
}
}
}
const board = new DispatchBoard();
// Tonight's plan for the morning: rows of data, run at 8:00.
const plan = [["assign", 42, "Dana"], ["assign", 43, "Leo"], ["unassign", 42, ""]];
runPlan(board, plan);
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map<number, string>();
assign(pkg: number, driver: string): void { this.#drivers.set(pkg, driver); }
unassign(pkg: number): void { this.#drivers.delete(pkg); }
describe(): string {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
type Step = [action: string, pkg: number, driver: string];
function runPlan(board: DispatchBoard, plan: Step[]): void {
for (const [action, pkg, driver] of plan) {
switch (action) {
case "assign":
board.assign(pkg, driver);
console.log(`Assign package ${pkg} to ${driver}`);
break;
case "unassign":
board.unassign(pkg);
console.log(`Unassign package ${pkg}`);
break;
// Next month: "swap", and then an undo button.
}
}
}
const board = new DispatchBoard();
// Tonight's plan for the morning: rows of data, run at 8:00.
const plan: Step[] = [["assign", 42, "Dana"], ["assign", 43, "Leo"], ["unassign", 42, ""]];
runPlan(board, plan);
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
It works. Now look at what each new request does to it. "Swap two drivers' packages" needs a new case, and a row with two drivers, which the other rows don't have. "Unassign" already carries an empty driver it doesn't use. The log line is typed again in every case, and the button that assigns a package right away (not in the plan) has its own copy of "do it, then log it". An undo button is impossible: once board.Assign has run, nothing is left that says what happened, or how to take it back.
- The symptom: actions stored as rows of data and run by a
switchon the action's name, with the log line typed again in each case, and actions that leave no trace once they've run. - The cause: an action is a method call. A call happens and is gone, so there's nothing to store, queue or take back, and the plan fakes one with data and a type code.
What would you try?
One more case for each new action. That's how the runner grew to two, and every new action edits the one method that every action runs through.
A row with every field any action might need: two packages, two drivers, a reason. Each kind of action then ignores most of its row, and the row means nothing without the switch that reads it.
Skip the plan: have the dispatcher come in at 8:00 and click the buttons then. It's a real choice, and it's exactly the job the plan was meant to save.
What we want is for each action to be a thing you can hold, one that knows how to run itself and how to describe itself, so the runner never needs to know what kinds there are.
The fix: an action you can hold
A universal remote's "movie night" button works this way. You program it once: TV on, lights down, sound bar on. The button doesn't do those things when you program it; it holds them, and runs them in order whenever you press it, tomorrow or next week. Each step is something stored, waiting to be done.

In code, each action becomes an object. AssignPackage holds the board, the package and the driver, and has two methods: Execute does the action, and Describe says what it is. UnassignPackage keeps the same promise. The plan is a list of these objects, and the runner calls Describe and Execute on each one, without knowing which kind it has.

DispatchBoard board = new DispatchBoard();
// Tonight's plan: each action is an object, made now, run at 8:00.
List<IDispatchCommand> plan = new List<IDispatchCommand>
{
new AssignPackage(board, 42, "Dana"),
new AssignPackage(board, 43, "Leo"),
new UnassignPackage(board, 42),
};
RunPlan(plan);
Console.WriteLine(board.Describe());
// The runner knows only the promise, never the kinds of action.
void RunPlan(List<IDispatchCommand> plan)
{
foreach (IDispatchCommand command in plan)
{
Console.WriteLine(command.Describe());
command.Execute();
}
}
interface IDispatchCommand
{
void Execute();
string Describe();
}
class AssignPackage : IDispatchCommand
{
private readonly DispatchBoard board;
private readonly int package;
private readonly string driver;
public AssignPackage(DispatchBoard board, int package, string driver)
{
this.board = board; this.package = package; this.driver = driver;
}
public void Execute() => board.Assign(package, driver);
public string Describe() => quot;Assign package {package} to {driver}";
}
class UnassignPackage : IDispatchCommand
{
private readonly DispatchBoard board;
private readonly int package;
public UnassignPackage(DispatchBoard board, int package)
{
this.board = board; this.package = package;
}
public void Execute() => board.Unassign(package);
public string Describe() => quot;Unassign package {package}";
}
class DispatchBoard
{
private readonly SortedDictionary<int, string> drivers = new SortedDictionary<int, string>();
public void Assign(int package, string driver) => drivers[package] = driver;
public void Unassign(int package) => drivers.Remove(package);
public string Describe() => "Board: " + string.Join(", ", drivers.Select(pair => quot;package {pair.Key} with {pair.Value}"));
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
interface DispatchCommand {
void execute();
String describe();
}
class DispatchBoard {
private final TreeMap<Integer, String> drivers = new TreeMap<>();
void assign(int pkg, String driver) { drivers.put(pkg, driver); }
void unassign(int pkg) { drivers.remove(pkg); }
String describe() {
List<String> lines = new ArrayList<>();
drivers.forEach((pkg, driver) -> lines.add("package " + pkg + " with " + driver));
return "Board: " + String.join(", ", lines);
}
}
record AssignPackage(DispatchBoard board, int pkg, String driver) implements DispatchCommand {
public void execute() { board.assign(pkg, driver); }
public String describe() { return "Assign package " + pkg + " to " + driver; }
}
record UnassignPackage(DispatchBoard board, int pkg) implements DispatchCommand {
public void execute() { board.unassign(pkg); }
public String describe() { return "Unassign package " + pkg; }
}
// The runner knows only the promise, never the kinds of action.
void runPlan(List<DispatchCommand> plan) {
for (DispatchCommand command : plan) {
IO.println(command.describe());
command.execute();
}
}
void main() {
DispatchBoard board = new DispatchBoard();
// Tonight's plan: each action is an object, made now, run at 8:00.
List<DispatchCommand> plan = List.of(
new AssignPackage(board, 42, "Dana"),
new AssignPackage(board, 43, "Leo"),
new UnassignPackage(board, 42));
runPlan(plan);
IO.println(board.describe());
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard:
def __init__(self):
self.drivers = {}
def assign(self, package, driver):
self.drivers[package] = driver
def unassign(self, package):
del self.drivers[package]
def describe(self):
return "Board: " + ", ".join(f"package {p} with {self.drivers[p]}" for p in sorted(self.drivers))
# Every command keeps the same promise: execute() and describe().
class AssignPackage:
def __init__(self, board, package, driver):
self.board = board
self.package = package
self.driver = driver
def execute(self):
self.board.assign(self.package, self.driver)
def describe(self):
return f"Assign package {self.package} to {self.driver}"
class UnassignPackage:
def __init__(self, board, package):
self.board = board
self.package = package
def execute(self):
self.board.unassign(self.package)
def describe(self):
return f"Unassign package {self.package}"
# The runner knows only the promise, never the kinds of action.
def run_plan(plan):
for command in plan:
print(command.describe())
command.execute()
board = DispatchBoard()
# Tonight's plan: each action is an object, made now, run at 8:00.
plan = [AssignPackage(board, 42, "Dana"), AssignPackage(board, 43, "Leo"), UnassignPackage(board, 42)]
run_plan(plan)
print(board.describe())
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map();
assign(pkg, driver) { this.#drivers.set(pkg, driver); }
unassign(pkg) { this.#drivers.delete(pkg); }
describe() {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
// Every command keeps the same promise: execute() and describe().
class AssignPackage {
constructor(board, pkg, driver) { this.board = board; this.pkg = pkg; this.driver = driver; }
execute() { this.board.assign(this.pkg, this.driver); }
describe() { return `Assign package ${this.pkg} to ${this.driver}`; }
}
class UnassignPackage {
constructor(board, pkg) { this.board = board; this.pkg = pkg; }
execute() { this.board.unassign(this.pkg); }
describe() { return `Unassign package ${this.pkg}`; }
}
// The runner knows only the promise, never the kinds of action.
function runPlan(plan) {
for (const command of plan) {
console.log(command.describe());
command.execute();
}
}
const board = new DispatchBoard();
// Tonight's plan: each action is an object, made now, run at 8:00.
const plan = [new AssignPackage(board, 42, "Dana"), new AssignPackage(board, 43, "Leo"), new UnassignPackage(board, 42)];
runPlan(plan);
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map<number, string>();
assign(pkg: number, driver: string): void { this.#drivers.set(pkg, driver); }
unassign(pkg: number): void { this.#drivers.delete(pkg); }
describe(): string {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
interface DispatchCommand {
execute(): void;
describe(): string;
}
class AssignPackage implements DispatchCommand {
board: DispatchBoard;
pkg: number;
driver: string;
constructor(board: DispatchBoard, pkg: number, driver: string) { this.board = board; this.pkg = pkg; this.driver = driver; }
execute(): void { this.board.assign(this.pkg, this.driver); }
describe(): string { return `Assign package ${this.pkg} to ${this.driver}`; }
}
class UnassignPackage implements DispatchCommand {
board: DispatchBoard;
pkg: number;
constructor(board: DispatchBoard, pkg: number) { this.board = board; this.pkg = pkg; }
execute(): void { this.board.unassign(this.pkg); }
describe(): string { return `Unassign package ${this.pkg}`; }
}
// The runner knows only the promise, never the kinds of action.
function runPlan(plan: DispatchCommand[]): void {
for (const command of plan) {
console.log(command.describe());
command.execute();
}
}
const board = new DispatchBoard();
// Tonight's plan: each action is an object, made now, run at 8:00.
const plan: DispatchCommand[] = [new AssignPackage(board, 42, "Dana"), new AssignPackage(board, 43, "Leo"), new UnassignPackage(board, 42)];
runPlan(plan);
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
The same four lines, and the switch is gone. Next month's "swap" is one new class that keeps the same promise; RunPlan doesn't change. The button that assigns right away makes an AssignPackage and runs it the same way, so its log line comes from the same Describe. And because each action is now an object that's still there after it runs, it can be kept, which is where the next lesson's undo button comes from.
Here is what happens to one action, in the order things call each other:

The modern version: a command is a function with a label
A command with one method to run is, underneath, one function. So a plan can hold functions, each with the line it logs:
DispatchBoard board = new DispatchBoard();
// Each command: a label to log, and a function to run later.
List<(string Description, Action Execute)> plan = new List<(string, Action)>
{
("Assign package 42 to Dana", () => board.Assign(42, "Dana")),
("Assign package 43 to Leo", () => board.Assign(43, "Leo")),
("Unassign package 42", () => board.Unassign(42)),
};
foreach ((string description, Action execute) in plan)
{
Console.WriteLine(description);
execute();
}
Console.WriteLine(board.Describe());
class DispatchBoard
{
private readonly SortedDictionary<int, string> drivers = new SortedDictionary<int, string>();
public void Assign(int package, string driver) => drivers[package] = driver;
public void Unassign(int package) => drivers.Remove(package);
public string Describe() => "Board: " + string.Join(", ", drivers.Select(pair => quot;package {pair.Key} with {pair.Value}"));
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
// Each command: a label to log, and a function to run later.
record Command(String description, Runnable execute) { }
class DispatchBoard {
private final TreeMap<Integer, String> drivers = new TreeMap<>();
void assign(int pkg, String driver) { drivers.put(pkg, driver); }
void unassign(int pkg) { drivers.remove(pkg); }
String describe() {
List<String> lines = new ArrayList<>();
drivers.forEach((pkg, driver) -> lines.add("package " + pkg + " with " + driver));
return "Board: " + String.join(", ", lines);
}
}
void main() {
DispatchBoard board = new DispatchBoard();
List<Command> plan = List.of(
new Command("Assign package 42 to Dana", () -> board.assign(42, "Dana")),
new Command("Assign package 43 to Leo", () -> board.assign(43, "Leo")),
new Command("Unassign package 42", () -> board.unassign(42)));
for (Command command : plan) {
IO.println(command.description());
command.execute().run();
}
IO.println(board.describe());
}
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard:
def __init__(self):
self.drivers = {}
def assign(self, package, driver):
self.drivers[package] = driver
def unassign(self, package):
del self.drivers[package]
def describe(self):
return "Board: " + ", ".join(f"package {p} with {self.drivers[p]}" for p in sorted(self.drivers))
board = DispatchBoard()
# Each command: a label to log, and a function to run later.
plan = [
("Assign package 42 to Dana", lambda: board.assign(42, "Dana")),
("Assign package 43 to Leo", lambda: board.assign(43, "Leo")),
("Unassign package 42", lambda: board.unassign(42)),
]
for description, execute in plan:
print(description)
execute()
print(board.describe())
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map();
assign(pkg, driver) { this.#drivers.set(pkg, driver); }
unassign(pkg) { this.#drivers.delete(pkg); }
describe() {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
const board = new DispatchBoard();
// Each command: a label to log, and a function to run later.
const plan = [
{ description: "Assign package 42 to Dana", execute: () => board.assign(42, "Dana") },
{ description: "Assign package 43 to Leo", execute: () => board.assign(43, "Leo") },
{ description: "Unassign package 42", execute: () => board.unassign(42) },
];
for (const command of plan) {
console.log(command.description);
command.execute();
}
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
class DispatchBoard {
#drivers = new Map<number, string>();
assign(pkg: number, driver: string): void { this.#drivers.set(pkg, driver); }
unassign(pkg: number): void { this.#drivers.delete(pkg); }
describe(): string {
const pkgs = [...this.#drivers.keys()].sort((a, b) => a - b);
return "Board: " + pkgs.map((pkg) => `package ${pkg} with ${this.#drivers.get(pkg)}`).join(", ");
}
}
// Each command: a label to log, and a function to run later.
type Command = { description: string; execute: () => void };
const board = new DispatchBoard();
const plan: Command[] = [
{ description: "Assign package 42 to Dana", execute: () => board.assign(42, "Dana") },
{ description: "Assign package 43 to Leo", execute: () => board.assign(43, "Leo") },
{ description: "Unassign package 42", execute: () => board.unassign(42) },
];
for (const command of plan) {
console.log(command.description);
command.execute();
}
console.log(board.describe());
Assign package 42 to Dana
Assign package 43 to Leo
Unassign package 42
Board: package 43 with Leo
All three versions print the same lines. The functions hold on to the board, the package and the driver they were written with (a function that keeps the values around it like this is called a closure), so each one is still a whole action, ready to run later. This version is shorter, and it's enough for a plan or a queue. When an action has to be undone, though, it needs a second function that knows how to reverse it, and a class that keeps the two together is often clearer. That's the next lesson.
Where the languages differ. C# uses the built-in Action for "a function that takes nothing and returns nothing", and Java uses Runnable; Java's switch with -> needs a default. Python and JavaScript put the label and the function side by side in a tuple or an object; TypeScript names that shape with a type.
How it got its name
Each object is a command: an order to do one thing, given now and carried out whenever whoever holds it says so. Turning an action into an object like this follows the Command pattern, from the original 1994 book. The object that runs commands (the plan runner) is called the invoker, and the one the command acts on (the board) the receiver.
Where you've already used it
setTimeout(() => ..., 1000)in JavaScript: you hand over an action now, and it runs later.- A background job queue ("send this email in five minutes"): each job is stored, then run by a worker.
- Ctrl+Z in any editor: each change you make is kept as a command, so it can be taken back.
When not to use it
- When an action always runs right away, once, and nobody needs to store, log or undo it. A direct call is easier to read.
- When a function is enough. For a plan or a queue, a list of functions (the modern version) does the job without a class for each action.
The cost: a class for every kind of action, and one more jump for the reader, from the button to the command to the board.
How often you'll meet it: now and then as classes, and every day as functions handed over to run later (our estimate).
Check yourself
2 questions to try on the lesson page.
So what
When an action has to be stored, queued, logged or run later, a method call isn't enough, because a call is gone once it's made. Make the action an object, or a function with a label, and it becomes something you can hold.