Programming Search⌘K

Patterncore

Command pattern

Also called Command, Action, Transaction, command object.

A request becomes an object that holds the operation and its arguments. The object can be stored, queued, logged, and run later, and with a second operation it can be undone.

Family
behavioral-design
Intent
Encapsulate a request as an object, so that code can pass requests as values, queue them or log them, and undo them.
Also called
Action, Transaction
Refactorings
Replace function with command, Replace command with function, Replace conditional dispatcher with command

Intent

Encapsulate a request as an object. Code can then pass requests as values, put them in a queue or a log, and support operations that can be undone.1 The object holds what to do and the data that it needs. The code that runs it does not need to know what it does.

Problem

A user interface toolkit has menus and buttons. The toolkit's author writes the menu item, but not the operation that the item runs. A text editor that uses the toolkit wants one item to save the file and another to paste text. The menu item must run a request that it knows nothing about. Design Patterns starts from this problem.1

An editor also wants undo. To undo a change, the program must know what the change was and how to reverse it. A change that is only a method call is gone after the call returns. Nothing remains to undo.

So the forces are these. The code that triggers a request must not depend on the code that does the work. A request must exist after it runs, so that it can be undone, done again, logged, or sent to another place. And the requests must have one interface, so that one history can hold all of them.

Solution

Design Patterns names five participants.1

  • Command declares an operation to execute, and often one to undo.
  • ConcreteCommand binds a receiver to an action. It holds the receiver and the arguments, and calls the receiver in execute.
  • Client makes a concrete command and sets its receiver.
  • Invoker asks the command to run. A menu item, a button, a queue and a history are invokers.
  • Receiver knows how to do the work. In the examples it is the text buffer.

The invoker calls execute and nothing else. It does not know the receiver or the action. A history is an invoker that keeps each command after it runs, so that it can call undo later.

Commands and closures

A command with only execute is a function value with its arguments bound. Norvig lists Command among the four patterns that first-class functions make less complex, and he describes a closure as behaviour with state data attached.2 In Python, a menu can hold functions. functools.partial binds the arguments of a function that takes them:13

from functools import partial


def save(path):
    print(f"saved {path}")


def quit_editor():
    print("bye")


menu = {"Save": partial(save, "notes.txt"), "Quit": quit_editor}
queue = [menu["Save"], menu["Quit"]]  # the invoker knows only "call it"
for command in queue:
    command()
Output
saved notes.txt
bye

Undo needs a second operation, so a single function is not enough. There are three ways to give it. A pair of closures shares the state that undo needs. An object has two methods and fields for that state. And a command can return its inverse when it runs, so that undo is a call to the returned command. Pike used the last form for options in Go. Each option sets a value and returns an option that restores the previous value.12 The Python example file uses it for editing commands.

Need A function value A command object
run later, queue, pass as an argument yes yes
undo needs a second function, or a function that returns its inverse an undo method
inspect, print, compare, serialize no; a closure is opaque yes, when the command is data
a command type that the compiler checks a function type an interface or an enum

The Rust example makes the commands an enum. A command is data that the program can print and store, and the editor passes the buffer to execute and undo. A closure in Rust that captured &mut String would hold the borrow for as long as the history keeps it.

Undo and redo stacks

The examples keep two stacks. The rules are short:

  • Run a command: execute it, push it on the undo stack, and clear the redo stack.
  • Undo: pop from the undo stack, call undo, and push the command on the redo stack.
  • Redo: pop from the redo stack, call execute again, and push it on the undo stack.

A single list with an index does the same work. The commands before the index can be undone, and the commands after it can be redone. IDLE, the editor that comes with CPython, keeps an undolist and a pointer. When a command is added, self.undolist[self.pointer:] = [cmd] drops the commands after the pointer.5 The Swing UndoManager trims the edits from indexOfNextAdd to the end in addEdit.8 IDLE also limits the length of the list, and merges a typed character into the previous insert command, so one undo removes a word and not one letter.5

Example

The example files run one script on a text buffer. They append "hello" and " world", delete five characters, undo twice, and redo once. Then they append "!", which clears the redo stack, so the last redo has nothing to do:

Language Form
Python closures; each command returns its inverse when it runs
JavaScript object literals with execute and undo closures that share a variable
TypeScript an interface and a class for each command
Java an interface, a record for Append and a class for Delete
C# an interface and classes with primary constructors
C++ a struct of two std::function values
C a struct with a pointer to a table of functions
Go an interface and a struct with pointer receivers for each command
Rust an enum of commands as data, run by the editor
PythonGitHub
from collections.abc import Callable

# A command runs once and returns the command that reverses it.
Command = Callable[[], "Command"]


class Buffer:
    def __init__(self) -> None:
        self.text = ""


def append(buffer: Buffer, text: str) -> Command:
    def run() -> Command:
        buffer.text += text
        return delete(buffer, len(text))

    return run


def delete(buffer: Buffer, count: int) -> Command:
    def run() -> Command:
        removed = buffer.text[len(buffer.text) - count :]  # read when the command runs
        buffer.text = buffer.text[: len(buffer.text) - count]
        return append(buffer, removed)

    return run


class History:
    def __init__(self) -> None:
        self.undo_stack: list[Command] = []
        self.redo_stack: list[Command] = []

    def run(self, command: Command) -> None:
        self.undo_stack.append(command())
        self.redo_stack.clear()  # a fresh command ends the redo branch

    def undo(self) -> bool:
        if not self.undo_stack:
            return False
        self.redo_stack.append(self.undo_stack.pop()())
        return True

    def redo(self) -> bool:
        if not self.redo_stack:
            return False
        self.undo_stack.append(self.redo_stack.pop()())
        return True


buffer, history = Buffer(), History()
show = lambda label: print(f'{label}: "{buffer.text}"')
history.run(append(buffer, "hello")); show("append")
history.run(append(buffer, " world")); show("append")
history.run(delete(buffer, 5)); show("delete")
history.undo(); show("undo")
history.undo(); show("undo")
history.redo(); show("redo")
history.run(append(buffer, "!")); show("append")
if not history.redo():
    print("redo: nothing to redo")
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. A command is a closure. It holds the buffer and its argument, and it runs when it is called.
  • Each command returns its inverse when it runs. The inverse of append is a delete of the same length, and the inverse of delete is an append of the removed text. Undo calls the inverse and gets back a command that redoes the change. This is the shape of the self-referential options of Rob Pike (see the node).
  • delete reads the text to remove when it runs, not when it is created. The node shows the bug that the other order causes.
  • A class with do and undo methods is the classic form. IDLE, the editor that comes with CPython, uses that form in idlelib/undo.py.
#include <cstdio>
#include <functional>
#include <memory>
#include <string>
#include <vector>

// A command is a pair of functions that share state through captures.
struct Command {
    std::function<void()> execute;
    std::function<void()> undo;
};

Command append(std::string& text, std::string suffix) {
    return {[&text, suffix] { text += suffix; },
            [&text, suffix] { text.resize(text.size() - suffix.size()); }};
}

Command delete_last(std::string& text, std::size_t count) {
    auto removed = std::make_shared<std::string>();  // shared by the two lambdas
    return {[&text, count, removed] {
                *removed = text.substr(text.size() - count);
                text.resize(text.size() - count);
            },
            [&text, removed] { text += *removed; }};
}

class History {
public:
    void run(Command command) {
        command.execute();
        undo_.push_back(std::move(command));
        redo_.clear();
    }

    bool undo() { return move_top(undo_, redo_, &Command::undo); }
    bool redo() { return move_top(redo_, undo_, &Command::execute); }

private:
    static bool move_top(std::vector<Command>& from, std::vector<Command>& to, std::function<void()> Command::*step) {
        if (from.empty()) return false;
        Command command = std::move(from.back());
        from.pop_back();
        (command.*step)();
        to.push_back(std::move(command));
        return true;
    }

    std::vector<Command> undo_, redo_;
};

int main() {
    std::string text;
    History history;
    auto show = [&text](const char* label) { std::printf("%s: \"%s\"\n", label, text.c_str()); };
    history.run(append(text, "hello")); show("append");
    history.run(append(text, " world")); show("append");
    history.run(delete_last(text, 5)); show("delete");
    history.undo(); show("undo");
    history.undo(); show("undo");
    history.redo(); show("redo");
    history.run(append(text, "!")); show("append");
    if (!history.redo()) std::printf("redo: nothing to redo\n");
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. A command is a struct of two std::function values. Each lambda captures the receiver by reference and its arguments by value.
  • The two lambdas of delete_last must share the removed text. A std::shared_ptr holds it, so both lambdas see one string, and the string lives as long as the command.
  • The lambdas capture text by reference, so the commands must not outlive the string. Here both live in main. A history that outlives its document would hold dangling references.
  • A function named erase would lose to std::erase here. Argument-dependent lookup finds std::erase for a std::string argument, and its template parameter matches the int argument exactly. So the function is delete_last.
  • A pointer to member, &Command::undo, lets one function move a command between the stacks for both undo and redo.
JavaGitHub
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    static final class Buffer {
        final StringBuilder text = new StringBuilder();
    }

    interface Command {
        void execute();

        void undo();
    }

    record Append(Buffer buffer, String text) implements Command {
        public void execute() {
            buffer.text.append(text);
        }

        public void undo() {
            buffer.text.setLength(buffer.text.length() - text.length());
        }
    }

    static final class Delete implements Command {
        private final Buffer buffer;
        private final int count;
        private String removed = "";

        Delete(Buffer buffer, int count) {
            this.buffer = buffer;
            this.count = count;
        }

        public void execute() {
            int start = buffer.text.length() - count;
            removed = buffer.text.substring(start);
            buffer.text.setLength(start);
        }

        public void undo() {
            buffer.text.append(removed);
        }
    }

    static final class History {
        private final Deque<Command> undoStack = new ArrayDeque<>();
        private final Deque<Command> redoStack = new ArrayDeque<>();

        void run(Command command) {
            command.execute();
            undoStack.push(command);
            redoStack.clear();
        }

        boolean undo() {
            Command command = undoStack.poll();
            if (command == null) return false;
            command.undo();
            redoStack.push(command);
            return true;
        }

        boolean redo() {
            Command command = redoStack.poll();
            if (command == null) return false;
            command.execute();
            undoStack.push(command);
            return true;
        }
    }

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        History history = new History();
        history.run(new Append(buffer, "hello")); print("append", buffer);
        history.run(new Append(buffer, " world")); print("append", buffer);
        history.run(new Delete(buffer, 5)); print("delete", buffer);
        history.undo(); print("undo", buffer);
        history.undo(); print("undo", buffer);
        history.redo(); print("redo", buffer);
        history.run(new Append(buffer, "!")); print("append", buffer);
        if (!history.redo()) System.out.println("redo: nothing to redo");
    }

    static void print(String label, Buffer buffer) {
        System.out.println(label + ": \"" + buffer.text + "\"");
    }
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. An interface with execute and undo. A record for the command whose state does not change. A class for the command that saves the removed text when it runs.
  • ArrayDeque serves as both stacks. push and poll work at the head, and poll returns null on an empty deque.
  • A command with no undo is a Runnable, and a lambda can implement it. Undo needs a second method, so the command needs its own interface or a pair of lambdas.
  • javax.swing.undo.UndoManager in the standard library keeps the edits in one list with an index, and trims the edits after the index when a fresh edit arrives.
#include <stdio.h>
#include <string.h>

enum { TEXT_MAX = 64, HISTORY_MAX = 16 };

struct buffer {
    char text[TEXT_MAX];
};

struct command;

struct command_ops {
    void (*execute)(struct command *c, struct buffer *b);
    void (*undo)(struct command *c, struct buffer *b);
};

struct command {
    const struct command_ops *ops;
    char arg[TEXT_MAX]; /* the text to append, or the text that a delete removed */
    size_t count;
};

static void append_execute(struct command *c, struct buffer *b) { strcat(b->text, c->arg); }
static void append_undo(struct command *c, struct buffer *b) { b->text[strlen(b->text) - strlen(c->arg)] = '\0'; }

static void delete_execute(struct command *c, struct buffer *b) {
    size_t start = strlen(b->text) - c->count;
    strcpy(c->arg, b->text + start);
    b->text[start] = '\0';
}
static void delete_undo(struct command *c, struct buffer *b) { strcat(b->text, c->arg); }

static const struct command_ops append_ops = {append_execute, append_undo};
static const struct command_ops delete_ops = {delete_execute, delete_undo};

static struct command append(const char *text) {
    struct command c = {&append_ops, "", 0};
    snprintf(c.arg, sizeof c.arg, "%s", text);
    return c;
}

static struct command delete(size_t count) { return (struct command){&delete_ops, "", count}; }

struct history {
    struct command undo[HISTORY_MAX], redo[HISTORY_MAX];
    int undo_count, redo_count;
};

static void run(struct history *h, struct buffer *b, struct command c) {
    c.ops->execute(&c, b);
    h->undo[h->undo_count++] = c;
    h->redo_count = 0;
}

static int undo(struct history *h, struct buffer *b) {
    if (h->undo_count == 0) return 0;
    struct command c = h->undo[--h->undo_count];
    c.ops->undo(&c, b);
    h->redo[h->redo_count++] = c;
    return 1;
}

static int redo(struct history *h, struct buffer *b) {
    if (h->redo_count == 0) return 0;
    struct command c = h->redo[--h->redo_count];
    c.ops->execute(&c, b);
    h->undo[h->undo_count++] = c;
    return 1;
}

static void show(const char *label, const struct buffer *b) { printf("%s: \"%s\"\n", label, b->text); }

int main(void) {
    struct buffer b = {""};
    struct history h = {0};
    run(&h, &b, append("hello")); show("append", &b);
    run(&h, &b, append(" world")); show("append", &b);
    run(&h, &b, delete(5)); show("delete", &b);
    undo(&h, &b); show("undo", &b);
    undo(&h, &b); show("undo", &b);
    redo(&h, &b); show("redo", &b);
    run(&h, &b, append("!")); show("append", &b);
    if (!redo(&h, &b)) printf("redo: nothing to redo\n");
    return 0;
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. A command is a struct with a pointer to a table of functions and the data that the functions need. This is how C code writes an object with virtual methods.
  • The commands are stored by value in fixed arrays, so the history needs no malloc and no free. The program does not check the limits of the arrays; real code must.
  • delete_execute saves the removed text in the command when it runs. The command is then copied to the undo stack with the text inside it.
var buffer = new Buffer();
var history = new History();
void Show(string label) => Console.WriteLine($"{label}: \"{buffer.Text}\"");

history.Run(new Append(buffer, "hello")); Show("append");
history.Run(new Append(buffer, " world")); Show("append");
history.Run(new Delete(buffer, 5)); Show("delete");
history.Undo(); Show("undo");
history.Undo(); Show("undo");
history.Redo(); Show("redo");
history.Run(new Append(buffer, "!")); Show("append");
if (!history.Redo()) Console.WriteLine("redo: nothing to redo");

class Buffer
{
    public string Text { get; set; } = "";
}

interface IUndoableCommand
{
    void Execute();
    void Undo();
}

sealed class Append(Buffer buffer, string text) : IUndoableCommand
{
    public void Execute() => buffer.Text += text;
    public void Undo() => buffer.Text = buffer.Text[..^text.Length];
}

sealed class Delete(Buffer buffer, int count) : IUndoableCommand
{
    private string _removed = "";

    public void Execute()
    {
        _removed = buffer.Text[^count..];
        buffer.Text = buffer.Text[..^count];
    }

    public void Undo() => buffer.Text += _removed;
}

sealed class History
{
    private readonly Stack<IUndoableCommand> _undo = new();
    private readonly Stack<IUndoableCommand> _redo = new();

    public void Run(IUndoableCommand command)
    {
        command.Execute();
        _undo.Push(command);
        _redo.Clear();
    }

    public bool Undo()
    {
        if (!_undo.TryPop(out var command)) return false;
        command.Undo();
        _redo.Push(command);
        return true;
    }

    public bool Redo()
    {
        if (!_redo.TryPop(out var command)) return false;
        command.Execute();
        _undo.Push(command);
        return true;
    }
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. An interface and a class for each command, with primary constructors for the receiver and the arguments.
  • Ranges such as [..^count] and [^count..] cut the end of the string, so each command is short.
  • System.Windows.Input.ICommand in .NET has Execute, CanExecute and a CanExecuteChanged event, and WPF buttons run commands through it. It has no Undo.
  • A delegate such as Action is a command with no undo. A pair of Action values is the closure form.
JavaScriptGitHub
class History {
  #undo = [];
  #redo = [];

  run(command) {
    command.execute();
    this.#undo.push(command);
    this.#redo.length = 0;
  }

  undo() {
    const command = this.#undo.pop();
    if (!command) return false;
    command.undo();
    this.#redo.push(command);
    return true;
  }

  redo() {
    const command = this.#redo.pop();
    if (!command) return false;
    command.execute();
    this.#undo.push(command);
    return true;
  }
}

const buffer = { text: "" };

const append = (text) => ({
  execute: () => {
    buffer.text += text;
  },
  undo: () => {
    buffer.text = buffer.text.slice(0, buffer.text.length - text.length);
  },
});

const remove = (count) => {
  let removed = "";
  return {
    execute: () => {
      removed = buffer.text.slice(buffer.text.length - count);
      buffer.text = buffer.text.slice(0, buffer.text.length - count);
    },
    undo: () => {
      buffer.text += removed;
    },
  };
};

const history = new History();
const show = (label) => console.log(`${label}: "${buffer.text}"`);
history.run(append("hello")); show("append");
history.run(append(" world")); show("append");
history.run(remove(5)); show("delete");
history.undo(); show("undo");
history.undo(); show("undo");
history.redo(); show("redo");
history.run(append("!")); show("append");
if (!history.redo()) console.log("redo: nothing to redo");
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. A command is an object literal with two functions, execute and undo. The two functions are closures over the same variables, so undo sees what execute saved.
  • remove keeps the removed text in a variable of the factory call. Each command has its own variable, because each call of remove makes a fresh scope.
  • delete is a reserved word in JavaScript, so the factory is named remove.
  • Private fields (#undo, #redo) keep the stacks inside History, so other code cannot push a command without running it.
TypeScriptGitHub
interface Command {
  execute(): void;
  undo(): void;
}

class Buffer {
  text = "";
}

class Append implements Command {
  private readonly buffer: Buffer;
  private readonly text: string;

  constructor(buffer: Buffer, text: string) {
    this.buffer = buffer;
    this.text = text;
  }

  execute(): void {
    this.buffer.text += this.text;
  }

  undo(): void {
    this.buffer.text = this.buffer.text.slice(0, this.buffer.text.length - this.text.length);
  }
}

class Delete implements Command {
  private readonly buffer: Buffer;
  private readonly count: number;
  private removed = "";

  constructor(buffer: Buffer, count: number) {
    this.buffer = buffer;
    this.count = count;
  }

  execute(): void {
    const text = this.buffer.text;
    this.removed = text.slice(text.length - this.count);
    this.buffer.text = text.slice(0, text.length - this.count);
  }

  undo(): void {
    this.buffer.text += this.removed;
  }
}

class History {
  private readonly undoStack: Command[] = [];
  private readonly redoStack: Command[] = [];

  run(command: Command): void {
    command.execute();
    this.undoStack.push(command);
    this.redoStack.length = 0;
  }

  undo(): boolean {
    const command = this.undoStack.pop();
    if (command === undefined) return false;
    command.undo();
    this.redoStack.push(command);
    return true;
  }

  redo(): boolean {
    const command = this.redoStack.pop();
    if (command === undefined) return false;
    command.execute();
    this.undoStack.push(command);
    return true;
  }
}

const buffer = new Buffer();
const history = new History();
const show = (label: string): void => console.log(`${label}: "${buffer.text}"`);
history.run(new Append(buffer, "hello")); show("append");
history.run(new Append(buffer, " world")); show("append");
history.run(new Delete(buffer, 5)); show("delete");
history.undo(); show("undo");
history.undo(); show("undo");
history.redo(); show("redo");
history.run(new Append(buffer, "!")); show("append");
if (!history.redo()) console.log("redo: nothing to redo");
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. The classic form: an interface for the command, and one class for each kind of command. The receiver, the buffer, is a constructor parameter.
  • The fields are declared and set in the constructor. Parameter properties, such as constructor(private readonly buffer: Buffer), are shorter, but Node.js rejects them when it strips types, because they generate code.
  • pop returns Command | undefined, so the compiler makes undo and redo handle an empty stack.
package main

import "fmt"

type Buffer struct{ Text string }

type Command interface {
	Execute()
	Undo()
}

type Append struct {
	buffer *Buffer
	text   string
}

func (a *Append) Execute() { a.buffer.Text += a.text }
func (a *Append) Undo()    { a.buffer.Text = a.buffer.Text[:len(a.buffer.Text)-len(a.text)] }

type Delete struct {
	buffer  *Buffer
	count   int
	removed string
}

func (d *Delete) Execute() {
	start := len(d.buffer.Text) - d.count
	d.removed = d.buffer.Text[start:]
	d.buffer.Text = d.buffer.Text[:start]
}

func (d *Delete) Undo() { d.buffer.Text += d.removed }

type History struct{ undo, redo []Command }

func (h *History) Run(c Command) {
	c.Execute()
	h.undo = append(h.undo, c)
	h.redo = h.redo[:0]
}

func (h *History) Undo() bool {
	if len(h.undo) == 0 {
		return false
	}
	c := h.undo[len(h.undo)-1]
	h.undo = h.undo[:len(h.undo)-1]
	c.Undo()
	h.redo = append(h.redo, c)
	return true
}

func (h *History) Redo() bool {
	if len(h.redo) == 0 {
		return false
	}
	c := h.redo[len(h.redo)-1]
	h.redo = h.redo[:len(h.redo)-1]
	c.Execute()
	h.undo = append(h.undo, c)
	return true
}

func main() {
	buffer := &Buffer{}
	history := &History{}
	show := func(label string) { fmt.Printf("%s: %q\n", label, buffer.Text) }
	history.Run(&Append{buffer, "hello"})
	show("append")
	history.Run(&Append{buffer, " world"})
	show("append")
	history.Run(&Delete{buffer: buffer, count: 5})
	show("delete")
	history.Undo()
	show("undo")
	history.Undo()
	show("undo")
	history.Redo()
	show("redo")
	history.Run(&Append{buffer, "!"})
	show("append")
	if !history.Redo() {
		fmt.Println("redo: nothing to redo")
	}
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
  • Verdict: idiom. An interface with two methods, and a struct for each kind of command. The methods have pointer receivers, so Delete can save the removed text in itself.
  • The two stacks are slices. h.redo[:0] empties the redo stack and keeps its array for reuse.
  • %q quotes the text with Go's escape rules. For this text the result is the same as the quotes in the other examples.
  • A command with no undo is a func(), and a slice of func() values is a queue of commands. Undo needs a second function, so this file uses an interface.
RustGitHub
// Commands are data. Undo needs the text that a delete removed, so Delete has a slot for it.
#[derive(Debug)]
enum Command {
    Append(String),
    Delete { count: usize, removed: String },
}

impl Command {
    fn execute(&mut self, text: &mut String) {
        match self {
            Command::Append(s) => text.push_str(s),
            Command::Delete { count, removed } => {
                let start = text.len() - *count;
                *removed = text.split_off(start);
            }
        }
    }

    fn undo(&self, text: &mut String) {
        match self {
            Command::Append(s) => text.truncate(text.len() - s.len()),
            Command::Delete { removed, .. } => text.push_str(removed),
        }
    }
}

#[derive(Default)]
struct Editor {
    text: String,
    undo: Vec<Command>,
    redo: Vec<Command>,
}

impl Editor {
    fn run(&mut self, mut command: Command) {
        command.execute(&mut self.text);
        self.undo.push(command);
        self.redo.clear();
    }

    fn undo(&mut self) -> bool {
        let Some(command) = self.undo.pop() else { return false };
        command.undo(&mut self.text);
        self.redo.push(command);
        true
    }

    fn redo(&mut self) -> bool {
        let Some(mut command) = self.redo.pop() else { return false };
        command.execute(&mut self.text);
        self.undo.push(command);
        true
    }

    fn show(&self, label: &str) {
        println!("{label}: \"{}\"", self.text);
    }
}

fn delete(count: usize) -> Command {
    Command::Delete { count, removed: String::new() }
}

fn main() {
    let mut editor = Editor::default();
    editor.run(Command::Append("hello".into()));
    editor.show("append");
    editor.run(Command::Append(" world".into()));
    editor.show("append");
    editor.run(delete(5));
    editor.show("delete");
    editor.undo();
    editor.show("undo");
    editor.undo();
    editor.show("undo");
    editor.redo();
    editor.show("redo");
    editor.run(Command::Append("!".into()));
    editor.show("append");
    if !editor.redo() {
        println!("redo: nothing to redo");
    }
    println!("{:?}", editor.undo.last());
}
Output
append: "hello"
append: "hello world"
delete: "hello "
undo: "hello world"
undo: "hello"
redo: "hello world"
append: "hello world!"
redo: nothing to redo
Some(Append("!"))
  • Verdict: idiom. A command is a value of an enum. It holds no reference to the buffer. The editor passes &mut String to execute and undo, so the borrow checker sees one owner of the text.
  • A closure that captured &mut String would hold a mutable borrow for as long as the command lives, and the history keeps commands for a long time. Commands as data avoid that problem.
  • An enum can be printed, compared, stored and sent to another thread with derives. The last line prints the command on top of the undo stack.
  • std::process::Command in the standard library is not this pattern. It is a builder for a child process.

Consequences

Design Patterns lists these consequences.1 Command decouples the object that invokes the operation from the one that knows how to do it. Commands are objects, so code can pass them around and extend them like other objects. Commands can be put together into a composite command. And a kind of command can be added with no change to the existing classes.

The costs are classes and state. In a language without closures, each action needs its own class. A command that can be undone must save the state that undo needs, and it must save it at the right moment.

Save the state when the command runs, not when it is created. A delete command must save the text it removes. If it reads the text when the command object is made, and other commands run between that time and execute, it saves the wrong text. This macro command makes both commands first and runs them later:

This code runs but gives a wrong answer on purpose.

class Buffer:
    text = "hello"


def append(buffer, text):
    def do():
        buffer.text += text

    def undo():
        buffer.text = buffer.text[: len(buffer.text) - len(text)]

    return do, undo


def delete(buffer, count):
    removed = buffer.text[len(buffer.text) - count :]  # read too early: the append has not run yet

    def do():
        buffer.text = buffer.text[: len(buffer.text) - count]

    def undo():
        buffer.text += removed

    return do, undo


buffer = Buffer()
macro = [append(buffer, " world"), delete(buffer, 5)]
for do, _ in macro:
    do()
print(f'after the macro: "{buffer.text}"')
_, undo_delete = macro[-1]
undo_delete()
print(f'after undo of the delete: "{buffer.text}"')
Output
after the macro: "hello "
after undo of the delete: "hello hello"

The undo of the delete should give back "hello world". The delete saved "hello" when it was created, not "world", so its undo adds the wrong text. The fix moves the read into do, as the example files do. The order of undo matters too. A macro undoes its commands in reverse order, because each command assumes the state that the commands before it left. IDLE's CommandSequence copies its list, reverses it, and undoes each command.7

Clear the redo stack when a command runs. The redo stack holds the commands that undo reversed. They assume the state that existed before the undo. After another command runs, that state is gone. A history that keeps the redo stack applies an old command to a state it was not made for:

This code runs but gives a wrong answer on purpose.

class History:
    def __init__(self, buffer):
        self.buffer = buffer
        self.undo_stack, self.redo_stack = [], []

    def append(self, text):
        self.buffer.append(text)
        self.undo_stack.append(text)  # the redo stack is not cleared

    def undo(self):
        text = self.undo_stack.pop()
        self.buffer.pop()
        self.redo_stack.append(text)

    def redo(self):
        self.append(self.redo_stack.pop())


words = []
history = History(words)
history.append("hello")
history.append("world")
history.undo()
history.append("there")
history.redo()  # this should do nothing
print(" ".join(words))
Output
hello there world

The user undid "world" and typed "there". The redo then brought back "world" on top of the edit. Both IDLE and Swing drop the commands after the current position when a command is added.58

Undo can drift. When undo computes the old state from the new one, small differences can build up over many cycles of undo and redo. Design Patterns calls this error accumulation and suggests that a command save enough state to restore the receiver exactly. A memento of the receiver's state does this.1

Commands with references live long. A history keeps commands for the life of the document. Each command keeps its receiver alive, and in C++ a command that captures a reference must not outlive its receiver. Limit the length of the history, as IDLE does.5

When not to use it

Do not write a command class for a callback that is never undone, stored or logged. Pass a function. Fowler's refactoring Replace Command with Function goes in this direction, and it is the inverse of Replace Function with Command.43

Do not use commands for undo when the state is small. A program can save a copy of the whole state before each change and restore it on undo. This needs no inverse operations, so it cannot have the bugs above. Commands pay off when the state is large and each change is small.

Do not turn each method call into a command object only for uniformity. The indirection hides what the code does, and a reader must find the class of each command to follow the program.

Composite: macro commands. A macro command holds a list of commands and runs them in order. Its undo runs their undo operations in reverse order. Design Patterns calls it MacroCommand.1 IDLE's CommandSequence is one, and it lets a set of edits be undone as a unit.7 See Composite pattern.

Memento. A command can save a memento of the receiver's state before it runs, and restore it on undo. This trades memory for exact undo.1

Prototype. A command that the program will change after it runs must be copied before it goes into the history. Design Patterns lists Prototype for this use.1

Strategy. Both patterns put behaviour in an object. A strategy answers how one known task is done, and the context calls it as part of its own work. A command is a whole request, and the invoker does not know what it does. Strategy has no undo. The Strategy pattern page covers strategies. Its section on closures made in a loop applies to commands too: a closure reads a variable when it runs, not when it is made.

Observer. An observer is often a command. The subject keeps a list of callbacks and runs each of them when it changes. The Observer pattern page covers that pattern.

Refactorings. Fowler's Replace Function with Command turns a long function into an object whose fields hold its local variables, so that its parts can be split into methods.315 Kerievsky's Replace Conditional Dispatcher with Command turns a chain of if statements on an action name into a map from names to command objects.14 See also Extract function.

Known uses

  • CPython: IDLE's UndoDelegator at v3.14.0 keeps an undolist and a pointer. addcmd runs a command, merges it with the previous one when it can, drops the commands after the pointer, and limits the list to max_undo. Its Command class has do, redo, undo and merge, and CommandSequence undoes a group in reverse order.567
  • OpenJDK Swing: javax.swing.undo.UndoManager holds UndoableEdit objects.9 Its addEdit at jdk-25+36 trims the edits after the current index, adds the edit, and then enforces its limit.8
  • .NET: System.Windows.Input.ICommand has Execute, CanExecute and a CanExecuteChanged event. WPF implements it in RoutedCommand and RoutedUICommand, and it gives the commanding behaviour of XAML buttons.10
  • Java: java.lang.Runnable is a command with one method and no undo. A class whose instances run on a thread implements it.11

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Command (Intent, Also Known As, Motivation, Participants, Collaborations, Consequences, Implementation, Related Patterns)
  2. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 10 (first-class functions make Command simpler) and slide 14 (closures)
  3. Martin Fowler, Refactoring catalog, Replace Function with Command, catalog entry (also known as Replace Method with Method Object; inverse of Replace Command with Function)
  4. Martin Fowler, Refactoring catalog, Replace Command with Function, catalog entry
  5. CPython v3.14.0 source, Lib/idlelib/undo.py, UndoDelegator.addcmd, undo_event and redo_event, lines 116 to 160
  6. CPython v3.14.0 source, Lib/idlelib/undo.py, class Command, lines 162 to 192
  7. CPython v3.14.0 source, Lib/idlelib/undo.py, class CommandSequence, lines 300 to 330
  8. OpenJDK jdk-25+36 source, javax/swing/undo/UndoManager.java, addEdit, lines 571 to 592
  9. Java SE 25 API, javax.swing.undo.UndoManager, class description
  10. .NET API reference, System.Windows.Input.ICommand, interface description, methods and events
  11. Java SE 25 API, java.lang.Runnable, interface description
  12. Rob Pike, Self-referential functions and the design of options, command center, January 24, 2014, the option type that returns an option to restore the previous value
  13. The Python Standard Library, functools, Python 3.14, functools.partial
  14. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 7, Simplification, Replace Conditional Dispatcher with Command
  15. Martin Fowler, Refactoring, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Replace Function with Command and Replace Command with Function

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/46Z0G2/text.yaml