Command: actions as objects

  • Lesson 20 of 32
  • 11 min
  • Intermediate
  • 14 steps

A button that calls a method directly leaves no trace, so there is no way to undo. You will turn each action into an object with `do` and `undo`, run it from a history and see where you already use this idea.

Commands in the history
—
Queued commands (example)
—
ButtonsDoc"Hello""Helloworld""Hel"stateDocrun()invokerexecuteCommandinvokerstoreinvokerrun()insertcommanddeleteLastcommandhandlercommandreducercommandinsertCommandinterfaceCommandbutton and shortcutchanges and forgetsA direct callhello.onclick = () =>doc.insert("Hello");shortcut("Alt+H", () =>doc.insert("Hello"));Ctrl+Zwhat was the last one?What you cannot doundoyou do not know what happenedrepeatyou do not have the datado it laterit already ranaction + datado · undoEveryone's contractinterface Command {do(): void;undo(): void;label: string;}do() adds the textdoc.text += sinsertconst insert = (doc: Doc, s: string): Command => ({label: `insert "${s}"`,▸do: () => { doc.text += s; },undo: () => { doc.text =▸doc.text.slice(0, -s.length); },});do() and keeps itcreates the commandThe invoker and its historyconst history: Command[] = [];const run = (c: Command) => {c.do();+history.push(c);};run(insert(doc, "Hello"));run(insert(doc, " world"));Ctrl+Zpop() and undo()Undo// Ctrl+Z▸const last = history.pop();▸last?.undo();// doc.text: "Hello"// history: [insert "Hello"]unchangedkeeps what it deleteddeleteLastconst deleteLast = (doc: Doc, n: number)▸: Command => { let removed = "";return { label: `delete ${n}`,do() {▸removed = doc.text.slice(-n);doc.text = doc.text.slice(0, -n); },undo() { doc.text += removed; } }; };undo without removedwhat do I give back?Two ways to undostoreshow to undowhat it wascostsone undo per commandmemory per snapshotpatternCommandMemento (module 5)offlinewaiting their turnA queue of commandsconst pending: Command[] = [];const later = (c: Command) =>pending.push(c);// when the network is back:▸pending.splice(0).forEach(run);"ext.hello"registered under an IDVS Code: one command per ID// in the extension:vscode.commands.registerCommand("ext.hello", () => { /* … */ });// from a menu, a shortcut or code:vscode.commands.executeCommand("ext.hello");{ type, payload }applies the actionRedux: the action is datastore.dispatch({type: "todos/added",payload: "Buy bread",});// the reducer gets the action// and returns the new statean object in your codenot a CQRS busThree wrong ideas«it is the CQRS command»same name, other scale«undo comes for free»every undo is written«it is always a class»a function may be enoughdirect callnot neededWhat you payone objectper actionone undocorrect in every commandone more hopwhen following the coderuns and remembersaction + dataCommand in a tableproblemthe action is lost once donesolutionan object with do and undoinvokerruns it without knowing what it doesgives youhistory, undo, queuedo not use itif none of that is needed
  • request
  • waiting in queue
  • failed request

Step 1 of 14

Problem

The button does the work

You have a text editor. The «Hello» button calls doc.insert("Hello") directly, and a keyboard shortcut calls the same thing on its own. It works: the text changes.

But the call happens and is gone. Nothing in the program remembers what was done or with which data.

What changed

  • doc.insert from the button and from the shortcut

Step 2 of 14

Problem

What do I undo?

Now you are asked for Ctrl+Z. The shortcut reaches Doc, but Doc only has its current text: it does not know what the last change was or how to revert it.

The same happens if you want to repeat the last action, show a history or keep actions to run them later. All of that needs something that does not exist yet: the action stored as data.

What changed

  • Ctrl+Z
  • Doc does not know what to revert

Step 3 of 14

Concept

The action becomes an object

The idea of Command: instead of running the action right away, you store it in an object. That object knows what it acts on (Doc), with which data ("Hello") and how to do and undo itself.

Every command meets the same interface, Command, with do() and undo(). So whoever runs them does not need to know what each one does.

What changed

  • interface Command
  • insert, the first command

Step 4 of 14

Technique

A command in a few lines

insert takes the document and the text, and returns an object with three things: a label for the history, do, which adds the text, and undo, which removes it.

Here it is a function that returns an object; an InsertCommand class works just as well. What matters is that `undo` reverses exactly what `do` did: it removes as many characters as it added.

What changed

  • do: adds s
  • undo: removes s.length characters

Step 5 of 14

Solution

Whoever runs it, remembers it

Something has to run it. run takes any Command, calls do() and stores it in history. The pattern calls it the invoker: it does not know whether the command inserts, deletes or changes the colour.

The button no longer calls Doc: it creates a command and hands it to run. After two actions, the document says «Hello world» and the history holds 2 commands.

What changed

  • run(c), the invoker
  • history
  • doc.insert from the button

Step 6 of 14

Solution

Ctrl+Z, at last

Undo is now taking the last command out of the history and calling its undo(). run does not need to know what it was: the command knows.

insert " world" removes its 6 characters and the document is back to «Hello». The history keeps 1 command. If you keep undone commands in another list, redo is calling their do() again.

What changed

  • insert " world" from the history
  • Doc back to "Hello"

Step 7 of 14

Technique

Another command, the same invoker

Add a command that deletes the last n characters. Its undo needs something insert did not: remembering what it deleted. That is why it stores it in removed before deleting.

run and the history do not change a single line. You run deleteLast(doc, 2): «Hello» becomes «Hel» and the history holds 2 commands again.

What changed

  • deleteLast, with removed
  • run, unchanged

Step 8 of 14

Trade-off

An undo that cannot undo

If deleteLast did not store removed, its undo would have nothing to give back and «Hel» would stay that way. Every command needs an exact inverse, and every inverse is code that can fail. Test it: do followed by undo leaves the document as it was.

There is another way to undo: before each command, keep a snapshot of the state (the whole doc.text) and restore it on undo. You write no inverses, but each snapshot takes memory. That idea has its own name, Memento, and you will see it in module 5.

What changed

  • undo without removed: cannot restore
  • alternative: a snapshot of the state

Step 9 of 14

Technique

Keeping them for later

Since a command is data, you do not have to run it right away. Imagine the editor saves to a server and goes offline: commands wait in a list and, when the network is back, they run in the same order.

If you store its name and data (not the functions), you can also write it to a log or send it to another process to run it there.

What changed

  • pending, a queue of commands

Step 10 of 14

Concept

You already use it: VS Code commands

In VS Code, an extension registers a function under a command ID with registerCommand. Menus, keyboard shortcuts and code itself run that command with executeCommand and the ID.

Whoever presses the shortcut does not know the function, only the ID. executeCommand acts as the invoker: it looks up the registered function and calls it. That is why one command can sit in a menu and on a shortcut at the same time.

What changed

  • run → executeCommand
  • the command → an ID and its handler

Step 11 of 14

Concept

A cousin in Redux: actions as data

In Redux, the only way to change the state is to dispatch an action: a plain object that describes what happened, like { type: "todos/added", payload: "Buy bread" }. The reducer is the one that makes the change.

The difference from the classic Command: the action is data only, with no do() or undo(). The code that applies it lives in the reducer, not in the action.

What changed

  • run → store.dispatch
  • do() → the reducer

Step 12 of 14

Concept

Three wrong ideas

«It is the CQRS command»: they share a name, not a scale. In CQRS (for example, with NestJS) a command is a message that a bus takes to the handler registered for its type, at the architecture level. The Command in this lesson is an object inside your code.

«Undo comes for free»: every undo has to be written and tested, or you keep snapshots of the state.

«It always takes a class»: with functions as values, a command without undo can be just () => doc.insert("Hello"). Peter Norvig already showed in 1996 that many patterns get simpler this way. You need the object once you add undo, a label or data to store.

Step 13 of 14

Trade-off

When not to use it and what it costs

If the action runs once, right away, and nobody needs to undo it, repeat it or store it, call the method directly. A command there is one more layer to read.

What you pay when you do use it: one object per action, one undo per command to keep correct and one more hop when following the code (run → do → Doc).

Step 14 of 14

Summary

Actions you can keep

When an action has to be undone, repeated, delayed or logged, turn it into an object with do() and undo(). An invoker runs it without knowing what it does and keeps it in a history.

The price is one object per action and a correct inverse in each one (or snapshots of the state, with Memento). If none of that is needed, the direct call is better.

You will learn

  • See why a direct call cannot be undone, repeated or delayed.
  • Turn an action into an object with `do()` and `undo()`.
  • Implement undo with a history of commands.
  • Recognise the idea in VS Code commands and Redux actions.
  • Know when a command is overkill and what it costs.