Notes
The problem
Here is the naive version. Each button handler changes the playlist directly. To support undo, we store a string saying what the last action was. But undo also needs the details: which song was removed, from which position. So the screen collects more and more fields, a switch grows for every kind of edit, and we only ever get one level of undo. Logging every edit or replaying them later is just as messy.
void onRemoveTapped(int i) {
playlist.remove(i);
lastAction = "remove"; // and the song?
}
void onUndoTapped() {
switch (lastAction) {
case "remove" -> ???
case "move" -> ???
}
} // one level of undo, at best The idea
The idea in one sentence: wrap a request in an object that knows how to carry it out. The object holds the target and the arguments, and, for undo, whatever it needs to reverse the action. The code that triggers a command does not need to know what it does. It only calls apply. And because the request is now an object, it can be stored, queued, logged, sent to another thread or combined with others.
- wrap a request in an object
- that knows how to carry it out
- the object can then be:
- stored for undo and redo
- put in a queue for later
- written to a log
- sent to another thread
- combined into a macro
The structure
The participants. PlaylistScreen is the client: it creates a command when the user taps a button. EditHistory is the invoker: it runs commands and remembers them for undo and redo. PlaylistEdit is the command interface, with apply and undo. AddSong, RemoveSong and MoveSong are concrete commands. Playlist is the receiver, the object that actually does the work. The invoker never touches the playlist directly.
The code: a command
The command interface has apply, undo and describe. Look at RemoveSong. It is created with the playlist and a position. When it is applied, it removes the song and keeps it in a field. Undo puts that exact song back at the same position. This is the heart of undo with commands: each command saves just enough information, at the moment it runs, to reverse itself exactly.
interface PlaylistEdit {
void apply(); void undo();
String describe(); }
final class RemoveSong implements ...
private String removed; // for undo
public void apply() {
removed = playlist.removeAt(index); }
public void undo() {
playlist.insertAt(index, removed); } The code: invoker
The invoker keeps two stacks. Run applies a command and pushes it onto the done stack. Undo pops the latest command, calls its undo, and pushes it onto the undone stack. Redo does the opposite. One rule is easy to forget: running a brand new command clears the redo stack. After you undo and then make a different edit, the old future no longer makes sense, so it must be thrown away.
Deque<PlaylistEdit> done =
new ArrayDeque<>(); // undo stack
Deque<PlaylistEdit> undone =
new ArrayDeque<>(); // redo stack
void run(PlaylistEdit e) {
e.apply(); done.push(e);
undone.clear(); } // new branch
void undo() { var e = done.pop();
e.undo(); undone.push(e); }
void redo() { var e = undone.pop();
e.apply(); done.push(e); } Run-through
Let us run it. The user taps remove on the second song. The screen builds a RemoveSong command for position one and hands it to the history. The history applies it, and the command removes the song from the playlist and remembers it. Then the user taps undo. The history pops that command and calls undo, and the command inserts the same song back at position one. The screen never wrote any undo logic.
Undo done right
A few rules make undo reliable. Capture what you need when the command is applied, not when it is created, because the playlist may have changed in between. Undo strictly in reverse order. Store values, not references to objects that might change later. Cap the history, for example at one hundred edits, and drop the oldest, or memory grows forever. And be honest: some actions, like sending an email, cannot be undone. Mark them, or undo them with a compensating action.
- capture state when applied,
- not when created
- undo in reverse order
- store values, not references
- to objects that may change
- cap the history (say 100)
- and drop the oldest
- some actions cannot be undone
- (sending an email): say so
- or compensate
Macro commands
Commands combine nicely. A macro command holds a list of other commands. Applying it applies each step in order, and undoing it undoes each step in reverse order. To the history it is just one command, so one tap of undo reverses a whole action, like add these three songs to the top. This is also how you build a recorded sequence that the user can replay.
record MacroEdit(String name,
List<PlaylistEdit> steps)
implements PlaylistEdit {
public void apply() {
steps.forEach(PlaylistEdit::apply); }
public void undo() {
for (int i = steps.size() - 1;
i >= 0; i--)
steps.get(i).undo(); }
} Queue it, log it
Undo is only one use. Because a command is an object, it can sit in a queue until a worker thread picks it up, or wait until a scheduled time. A failed command can simply be run again. Each command can be written to an append only log, and replaying that log rebuilds the state after a crash, which is how many databases and event sourced systems work. A mobile app can queue edits while offline and send them when the network comes back.
- queue: a worker takes commands
- off a queue and runs them
- schedule: run at a later time
- retry: run the same object
- again after a failure
- log: write each command to an
- append-only log; replay it
- to rebuild state after a crash
- offline: queue edits, sync
- them when back online
When to use it
Use Command when a request needs a life of its own: undo and redo, queues, scheduled jobs, retries, audit logs and replay, or when a button, a menu item and a keyboard shortcut should all trigger the same action. Skip it when you simply call a method and nothing is stored, delayed or reversed. Then a command class per action is extra ceremony that hides a one line call.
- use it for:
- undo and redo
- queues, schedules, retries
- audit logs and replay
- buttons and menus that share
- one action
- skip it when:
- the call is direct and final
- nothing is stored or undone
Command vs neighbours
How does Command differ from its neighbours? A strategy is a way of doing a job, like a shuffle rule, plugged into an object and used again and again. A command is one specific request, with its target and arguments, ready to run, store or undo. Memento also supports undo, but by saving a snapshot of the whole state. Command undo reverses each step instead, which is usually much smaller. The two are often combined when reversing a step is hard.
- Strategy: one way of doing a
- job, chosen and plugged in
- (a ShuffleRule)
- Command: one specific request,
- with its target and args,
- ready to run, store or undo
- Memento: undo by saving a
- snapshot of the whole state
- Command undo: reverse each
- step, usually much smaller
In Java
Java uses the idea everywhere. A Runnable or a Callable handed to an executor service is a command: a request wrapped in an object and queued for another thread. Swing has an Action interface, so one action object can back a button, a menu item and a keyboard shortcut. Swing's undo package has UndoableEdit, with undo and redo methods, and an UndoManager that keeps the history, which is the same design we just built.
- Runnable and Callable given
- to an ExecutorService:
- requests queued for threads
- Swing Action: one action for
- a button, menu and shortcut
- javax.swing.undo:
- UndoableEdit, UndoManager
- job and message queues in
- frameworks
In LLD interviews
In machine coding rounds, listen for undo, redo, queue, schedule, retry or audit. A text editor or drawing board is the classic undo and redo problem. In a chess game, each move is a command, so taking back a move is just undo. An elevator system can queue floor requests as command objects for the scheduler. A task scheduler runs jobs as commands. A banking design logs every transaction and reverses one with a compensating command.
- text editor: undo and redo
- drawing board or whiteboard
- chess or board games: take
- back a move
- elevator: floor requests
- queued for the scheduler
- task scheduler: jobs as
- commands
- bank: transactions with an
- audit log and reversal
Mistakes to avoid
Common mistakes. An undo that is not the exact inverse, such as removing by name when the playlist holds the same song twice. Forgetting to clear the redo stack after a new edit. Letting the history grow forever. A command that holds a reference to the whole screen instead of just the playlist and its arguments. And putting real logic in the invoker. The invoker should only run and remember. The command and the receiver do the work.
- undo that is not the exact
- inverse of apply
- forgetting to clear redo
- after a new edit
- unbounded history
- command holds the screen,
- not just what it needs
- logic in the invoker instead
- of the command or receiver