Command
Turning requests into objects — invokers and receivers, undo/redo stacks, macro commands, job queues, and how commands relate to callbacks and event sourcing.
Intent: encapsulate a request as an object, so you can parameterise clients with different requests, queue or log them, and support undoable operations.
Once an action is an object instead of a direct method call, you can store it, pass it around, execute it later, execute it on another machine, record it, and reverse it.
- Command: knows which receiver to call and with what arguments.
- Receiver: the object that actually performs the work (a document, a bank account).
- Invoker: triggers commands without knowing what they do (a toolbar button, a menu, a job runner).
Undo/redo in a text editor
interface Command {
void execute();
void undo();
}
class Document { // receiver
private final StringBuilder text = new StringBuilder();
void insert(int pos, String s) { text.insert(pos, s); }
void delete(int pos, int len) { text.delete(pos, pos + len); }
String slice(int pos, int len) { return text.substring(pos, pos + len); }
}
class InsertText implements Command {
private final Document doc; private final int pos; private final String s;
InsertText(Document doc, int pos, String s) { this.doc = doc; this.pos = pos; this.s = s; }
public void execute() { doc.insert(pos, s); }
public void undo() { doc.delete(pos, s.length()); }
}
class DeleteText implements Command {
private final Document doc; private final int pos, len;
private String deleted; // state needed to undo
DeleteText(Document doc, int pos, int len) { this.doc = doc; this.pos = pos; this.len = len; }
public void execute() { deleted = doc.slice(pos, len); doc.delete(pos, len); }
public void undo() { doc.insert(pos, deleted); }
}
class History { // invoker with undo/redo stacks
private final Deque<Command> undo = new ArrayDeque<>(), redo = new ArrayDeque<>();
void run(Command c) { c.execute(); undo.push(c); redo.clear(); }
void undo() { if (!undo.isEmpty()) { Command c = undo.pop(); c.undo(); redo.push(c); } }
void redo() { if (!redo.isEmpty()) { Command c = redo.pop(); c.execute(); undo.push(c); } }
}from dataclasses import dataclass, field
class Document:
def __init__(self): self.text = ""
def insert(self, pos, s): self.text = self.text[:pos] + s + self.text[pos:]
def delete(self, pos, n): self.text = self.text[:pos] + self.text[pos + n:]
@dataclass
class InsertText:
doc: Document
pos: int
s: str
def execute(self): self.doc.insert(self.pos, self.s)
def undo(self): self.doc.delete(self.pos, len(self.s))
@dataclass
class DeleteText:
doc: Document
pos: int
n: int
deleted: str = ""
def execute(self):
self.deleted = self.doc.text[self.pos:self.pos + self.n]
self.doc.delete(self.pos, self.n)
def undo(self): self.doc.insert(self.pos, self.deleted)
class History:
def __init__(self): self._undo, self._redo = [], []
def run(self, cmd):
cmd.execute(); self._undo.append(cmd); self._redo.clear()
def undo(self):
if self._undo:
cmd = self._undo.pop(); cmd.undo(); self._redo.append(cmd)
def redo(self):
if self._redo:
cmd = self._redo.pop(); cmd.execute(); self._undo.append(cmd)interface Command { execute(): void; undo(): void; }
class InsertText implements Command {
constructor(private doc: Doc, private pos: number, private s: string) {}
execute() { this.doc.insert(this.pos, this.s); }
undo() { this.doc.delete(this.pos, this.s.length); }
}
class History {
private undoStack: Command[] = [];
private redoStack: Command[] = [];
run(c: Command) { c.execute(); this.undoStack.push(c); this.redoStack = []; }
undo() { const c = this.undoStack.pop(); if (c) { c.undo(); this.redoStack.push(c); } }
redo() { const c = this.redoStack.pop(); if (c) { c.execute(); this.undoStack.push(c); } }
}Typing "Hi", deleting a word, then undoing twice walks back through the stack:
Macro commands
A composite command runs a list of commands as one and undoes them in reverse order — "apply formatting", recorded macros, database migration batches.
class Macro implements Command {
constructor(private steps: Command[]) {}
execute() { this.steps.forEach((c) => c.execute()); }
undo() { [...this.steps].reverse().forEach((c) => c.undo()); }
}Commands as messages: queues and jobs
A command that is serialisable (just a name plus data) can be queued and executed by another process:
{ "type": "SendWelcomeEmail", "userId": "u_42", "attempt": 1 }That's how background job systems work (Sidekiq, Celery, BullMQ): the web process creates a command; a worker executes it. Logging every command enables auditing and replay — the idea behind event sourcing and write-ahead logs. In CQRS, "commands" are requests to change state, handled separately from queries.
Commands vs callbacks
In languages with closures, a callback is a command with a single execute(): button.onClick(() => save()). You need explicit command classes when you also need undo, serialisation, metadata (name, timestamp, user) or queuing.
- Command turns a request into an object: execute later, queue, log, undo.
- Undo/redo uses two stacks; commands store what they need to reverse themselves.
- Macro commands compose commands and undo in reverse.
- Serialisable commands power job queues, audit logs and event sourcing.
- A closure is a lightweight command; use classes when you need undo or serialisation.
QHow would you implement undo/redo?medium
Model each user action as a command with execute() and undo(), storing whatever state is needed to reverse it. Keep an undo stack and a redo stack: running a command pushes it on the undo stack and clears redo; undo pops, calls undo() and pushes onto redo; redo does the reverse. Alternatively store snapshots (memento) before each action, trading memory for simplicity.