Command

Turning requests into objects — invokers and receivers, undo/redo stacks, macro commands, job queues, and how commands relate to callbacks and event sourcing.

Intermediate 2 min readLesson 16 of 24 Interview Q&A

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.

execute()Clientcreates commandsInvokerbutton · queue · schedulerCommandexecute() · undo()Receiverdoes the real work
  • 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); } }
}

Typing "Hi", deleting a word, then undoing twice walks back through the stack:

Delete 6 @2← topInsert ' there' @2Insert 'Hi' @0
Undo stack: undo pops from the top and calls undo().

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.

TypeScript
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:

JSON
{ "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.

Key takeaways
  • 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.
Interview questions
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.