Polski

Article · Command · CQRS

Command: a request wrapped in an object

The Command pattern through a waiter's terminal in a pierogi place: every action on the ticket is an object with execute and undo, so it can be undone, redone, kept in a history and sent to a queue. Code in five languages.

By · · 12 min read

A waitress in Halina's pierogi place adds two portions of potato-and-cheese pierogi, a compote and a discount for a regular to the ticket. The customer changes their mind – the compote has to go, but the pierogi stay. Command turns every click into an object that knows how to execute itself and how to undo itself. Undo, history and the kitchen queue stop being separate problems.

2
stacks are enough for undo/redo – executed and undone commands
1
method the invoker knows – execute() – the rest lives in the command
∞
ways to use a request object – queue, log, macro, retry after a failure

The problem: a button that does everything itself

The terminal at the counter started with a single switch handling buttons:

terminal-before.ts
class Terminal {
  constructor(private readonly ticket: Ticket) {}

  onButton(action: string, payload: any): void {
    switch (action) {
      case 'add':      this.ticket.lines.push(payload); break;
      case 'remove':   this.ticket.lines.splice(payload.index, 1); break;
      case 'discount': this.ticket.discount = payload.percent; break;
      // undo? "Just delete the ticket and start again." – the waitress
    }
  }
}

The action logic lives in the button handler, so it cannot be used from anywhere else – say, from a keyboard shortcut or a phone app. There is no trace of what was done, so there is no undo. Nor can an action be postponed: when the kitchen printer is offline the order is lost, because the "action" only existed as a method call.

The solution: every action is an object

Every operation on the ticket becomes a class with an execute() method (and optionally undo()). The command object holds a reference to the receiver (the ticket) and all parameters. The terminal – the invoker – only runs commands and pushes them onto a history stack. Undo means popping a command off the stack and calling its undo().

Diagram: Running, undoing and redoing commands
Diagram: Participants of the Command pattern
RoleIn the exampleResponsibility
CommandCommandthe execute() / undo() interface
Concrete commandAddDish, SetDiscountthe request parameters and the knowledge of how to execute and undo it
ReceiverTicketthe object the command actually works on
InvokerTerminalruns commands and keeps the history
Clientthe button handlercreates a command and hands it to the invoker

Implementation in five languages

Every variant runs the same scenario: two lines, a discount, two undos and one redo. In TypeScript commands are plain objects created by functions, and the label shows that a command is also data – you can display the history or send it over the network.

Command – waiter's terminal

Terminal.cs
var ticket = new Ticket();
var terminal = new Terminal();
terminal.Run(new AddDish(ticket, "Ruskie", 2));
terminal.Run(new AddDish(ticket, "Kompot", 1));
terminal.Run(new SetDiscount(ticket, 10));
terminal.Undo();           // discount removed
terminal.Undo();           // kompot removed
terminal.Redo();           // kompot is back
Console.WriteLine(ticket); // Ruskie x2, Kompot x1, discount 0%

public interface ICommand
{
    void Execute();
    void Undo();
}

public sealed class Ticket
{
    public List<(string Dish, int Qty)> Lines { get; } = [];
    public int DiscountPercent { get; set; }

    public override string ToString() =>
        $"{string.Join(", ", Lines.Select(l => $"{l.Dish} x{l.Qty}"))}, discount {DiscountPercent}%";
}

public sealed class AddDish(Ticket ticket, string dish, int qty) : ICommand
{
    public void Execute() => ticket.Lines.Add((dish, qty));
    public void Undo() => ticket.Lines.RemoveAt(ticket.Lines.Count - 1); // undo runs in LIFO order
}

public sealed class SetDiscount(Ticket ticket, int percent) : ICommand
{
    private int _previous; // what Undo needs to restore

    public void Execute() => (_previous, ticket.DiscountPercent) = (ticket.DiscountPercent, percent);
    public void Undo() => ticket.DiscountPercent = _previous;
}

public sealed class Terminal
{
    private readonly Stack<ICommand> _done = new();
    private readonly Stack<ICommand> _undone = new();

    public void Run(ICommand command)
    {
        command.Execute();
        _done.Push(command);
        _undone.Clear(); // a new action invalidates the redo history
    }

    public void Undo() { if (_done.TryPop(out var c)) { c.Undo(); _undone.Push(c); } }

    public void Redo() { if (_undone.TryPop(out var c)) { c.Execute(); _done.Push(c); } }
}
terminal.ts
interface Command {
  readonly label: string; // commands are data: they can be listed, logged, sent
  execute(): void;
  undo(): void;
}

class Ticket {
  lines: { dish: string; qty: number }[] = [];
  discountPercent = 0;
}

const addDish = (ticket: Ticket, dish: string, qty: number): Command => ({
  label: `add ${dish} x${qty}`,
  execute: () => void ticket.lines.push({ dish, qty }),
  undo: () => void ticket.lines.pop(), // undo runs in LIFO order
});

const setDiscount = (ticket: Ticket, percent: number): Command => {
  let previous = 0;
  return {
    label: `discount ${percent}%`,
    execute: () => { previous = ticket.discountPercent; ticket.discountPercent = percent; },
    undo: () => { ticket.discountPercent = previous; },
  };
};

class Terminal {
  private done: Command[] = [];
  private undone: Command[] = [];

  run(command: Command): void {
    command.execute();
    this.done.push(command);
    this.undone = []; // a new action invalidates the redo history
  }

  undo(): void {
    const command = this.done.pop();
    if (command) { command.undo(); this.undone.push(command); }
  }

  redo(): void {
    const command = this.undone.pop();
    if (command) { command.execute(); this.done.push(command); }
  }

  get history(): string[] { return this.done.map((c) => c.label); }
}

const ticket = new Ticket();
const terminal = new Terminal();
terminal.run(addDish(ticket, 'Ruskie', 2));
terminal.run(addDish(ticket, 'Kompot', 1));
terminal.run(setDiscount(ticket, 10));
terminal.undo();
console.log(terminal.history); // ['add Ruskie x2', 'add Kompot x1']
Terminal.java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

interface Command {
    void execute();
    void undo();
}

class Ticket {
    final List<String> lines = new ArrayList<>();
    int discountPercent;

    @Override public String toString() { return lines + ", discount " + discountPercent + "%"; }
}

record AddDish(Ticket ticket, String dish, int qty) implements Command {
    public void execute() { ticket.lines.add(dish + " x" + qty); }
    public void undo() { ticket.lines.removeLast(); } // undo runs in LIFO order (Java 21+)
}

final class SetDiscount implements Command {
    private final Ticket ticket;
    private final int percent;
    private int previous; // what undo needs to restore

    SetDiscount(Ticket ticket, int percent) { this.ticket = ticket; this.percent = percent; }

    public void execute() { previous = ticket.discountPercent; ticket.discountPercent = percent; }
    public void undo() { ticket.discountPercent = previous; }
}

public class Terminal {
    private final Deque<Command> done = new ArrayDeque<>();
    private final Deque<Command> undone = new ArrayDeque<>();

    public void run(Command command) {
        command.execute();
        done.push(command);
        undone.clear(); // a new action invalidates the redo history
    }

    public void undo() { var c = done.poll(); if (c != null) { c.undo(); undone.push(c); } }

    public void redo() { var c = undone.poll(); if (c != null) { c.execute(); done.push(c); } }

    public static void main(String[] args) {
        var ticket = new Ticket();
        var terminal = new Terminal();
        terminal.run(new AddDish(ticket, "Ruskie", 2));
        terminal.run(new AddDish(ticket, "Kompot", 1));
        terminal.run(new SetDiscount(ticket, 10));
        terminal.undo();
        terminal.undo();
        terminal.redo();
        System.out.println(ticket); // [Ruskie x2, Kompot x1], discount 0%
    }
}
terminal.go
package main

import "fmt"

type Command interface {
	Execute()
	Undo()
}

type Ticket struct {
	Lines           []string
	DiscountPercent int
}

type AddDish struct {
	T    *Ticket
	Dish string
	Qty  int
}

func (c AddDish) Execute() { c.T.Lines = append(c.T.Lines, fmt.Sprintf("%s x%d", c.Dish, c.Qty)) }
func (c AddDish) Undo()    { c.T.Lines = c.T.Lines[:len(c.T.Lines)-1] } // undo runs in LIFO order

type SetDiscount struct {
	T        *Ticket
	Percent  int
	previous int // what Undo needs to restore
}

func (c *SetDiscount) Execute() { c.previous, c.T.DiscountPercent = c.T.DiscountPercent, c.Percent }
func (c *SetDiscount) Undo()    { c.T.DiscountPercent = c.previous }

type Terminal struct{ done, undone []Command }

func (t *Terminal) Run(c Command) {
	c.Execute()
	t.done = append(t.done, c)
	t.undone = nil // a new action invalidates the redo history
}

func move(from, to *[]Command, act func(Command)) {
	if len(*from) == 0 {
		return
	}
	c := (*from)[len(*from)-1]
	*from = (*from)[:len(*from)-1]
	act(c)
	*to = append(*to, c)
}

func (t *Terminal) Undo() { move(&t.done, &t.undone, Command.Undo) }
func (t *Terminal) Redo() { move(&t.undone, &t.done, Command.Execute) }

func main() {
	ticket := &Ticket{}
	var term Terminal
	term.Run(AddDish{ticket, "Ruskie", 2})
	term.Run(AddDish{ticket, "Kompot", 1})
	term.Run(&SetDiscount{T: ticket, Percent: 10})
	term.Undo()
	term.Undo()
	term.Redo()
	fmt.Println(ticket.Lines, ticket.DiscountPercent) // [Ruskie x2 Kompot x1] 0
}
terminal.py
from dataclasses import dataclass, field
from typing import Protocol


class Command(Protocol):
    def execute(self) -> None: ...
    def undo(self) -> None: ...


@dataclass
class Ticket:
    lines: list[str] = field(default_factory=list)
    discount_percent: int = 0


@dataclass
class AddDish:
    ticket: Ticket
    dish: str
    qty: int

    def execute(self) -> None:
        self.ticket.lines.append(f"{self.dish} x{self.qty}")

    def undo(self) -> None:
        self.ticket.lines.pop()  # undo runs in LIFO order


@dataclass
class SetDiscount:
    ticket: Ticket
    percent: int
    _previous: int = field(default=0, init=False, repr=False)  # what undo needs to restore

    def execute(self) -> None:
        self._previous, self.ticket.discount_percent = self.ticket.discount_percent, self.percent

    def undo(self) -> None:
        self.ticket.discount_percent = self._previous


class Terminal:
    def __init__(self) -> None:
        self._done: list[Command] = []
        self._undone: list[Command] = []

    def run(self, command: Command) -> None:
        command.execute()
        self._done.append(command)
        self._undone.clear()  # a new action invalidates the redo history

    def undo(self) -> None:
        if self._done:
            command = self._done.pop()
            command.undo()
            self._undone.append(command)

    def redo(self) -> None:
        if self._undone:
            command = self._undone.pop()
            command.execute()
            self._done.append(command)


ticket, terminal = Ticket(), Terminal()
terminal.run(AddDish(ticket, "Ruskie", 2))
terminal.run(AddDish(ticket, "Kompot", 1))
terminal.run(SetDiscount(ticket, 10))
terminal.undo()
terminal.undo()
terminal.redo()
print(ticket)  # Ticket(lines=['Ruskie x2', 'Kompot x1'], discount_percent=0)

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Two ways to undo
  • Inverse operation
  • State snapshot
  • Command as data: queues and retries
  • When to use it and when not to
  • Command vs a command in CQRS
  • Related patterns
  • In practice
  • Test yourself

Create a free account · Sign in