Ch.7: Design Patterns: Build Undo and Redo With Commands

Outline

Transcript

0:00 Command stores an action in an object, a bundle of information and instructions, so we can run it later. Undo reverses edits, but it breaks if we lose the information needed to go back. We'll build an editor that runs stored edits, undoes them and reapplies them with redo. Then we'll test what happens when the caller, the code requesting an edit, sends it twice. Imagine a user moving this blue shape 5 units to the right. Its horizontal position, x, starts at 10. The move by object stores the shape and the amount, plus 5. The shape is called the receiver because it performs the edit.

0:37 The arrow is a reference, a way to reach that same live shape. The name move by reads like an action, yet we've only stored one. The position still says 10. Does putting the operation in that object run any of its movement code? No. It keeps that shape reference and the movement amount. Execute is a separate method, and calling it asks the shape to add the saved amount. Now the result becomes 15. We can hand the object to other code before anything moves, which separates choosing an action from performing it.

1:09 The programming book Game Programming Patterns uses that separation to explain Command. Its discussion and the other references are linked in the description. We still have to write the behavior, which means giving the object a pattern name hasn't provided a working Undo button. Before adding undo, couldn't we just store a function, code we can call later? Yes. On a fresh shape, Python's lambda creates an unnamed function. The first line keeps it without calling it; the second runs it, changing 10 to 15.

1:39 My first thought is to keep the function because it already delays the move. What does making an object buy us here? Functions can support reversal too. Here the object keeps the shape, movement amount and undo operation together, so the code recording completed edits can hold one action and ask it to run or reverse. Next, reset the shape to 10 and create two fresh requests, plus 5 and plus 2. The pending list is our queue, the ordered requests waiting to run. Both are waiting, so the position hasn't changed.

2:12 History, our record of completed actions, starts empty. What does the runner, the code that runs waiting requests, do first? The runner selects the waiting plus 5. History calls execute on that command, which tells the shape to move. After success, history records the command, then the runner removes the pending item. Each arrow here means a call to the next box. So plus 5 reaches 15. Pending now holds plus 2, while Done holds the completed plus 5. The runner follows the same route for plus 2. Position reaches 17; Pending is empty, and Done holds both commands.

2:49 Suppose the first request had failed before moving the shape. Should it have disappeared from Pending anyway? No. Here the command reports it couldn't finish. That stops the call in History before recording and the runner's call before removal. Both requests remain waiting, neither reaches Done, and the shape hasn't moved. For example, a menu and a keyboard shortcut could create the same kind of request without owning the movement code themselves. Those callers can share the runner, and the completed commands give us something to undo.

3:19 Now return to the successful two-move example, where both edits were recorded. Our move adds a whole number amount, so its undo adds the opposite amount. At 17, subtract 2 to get 15, then subtract 5 to return to 10. History chooses the most recently completed action first. The next action to undo is the rightmost Done entry. If we throw it away afterward, what would Redo run? We keep the command in Undone, where Redo can find it. The code selects the last Done entry, runs its undo, and only then transfers it.

3:51 Keeping it until the reversal succeeds matters. If the reversal fails without altering the shape, this code leaves the entry where it was. Redo takes the most recently undone command and calls execute again. Watch the 5-unit movement return before the 2-unit movement, restoring 17. Now undo plus 2 once more, leaving 15. Suppose we make a different edit, plus 9. The position becomes 24, and history clears the old redo path. So pressing Redo cannot quietly add that abandoned plus 2 to our new edit.

4:23 Its empty list makes the attempt return false, leaving 24. That's our chosen rule. Qt, software used to build apps, also clears redo options after recording a new edit. Other history designs can retain alternatives. Those edits all succeeded. What happens if the next queued action reports failure after changing the shape? In this separate example, it moves 10 to 15 and then fails. Pending keeps the request, and Done stays empty. Does the shape go back to 10 too? No. It's still at 15, with the failed request left in Pending and nothing in Done. Keeping those lists unchanged hasn't reversed the movement.

5:00 Changing a color will force us to remember information the new value no longer contains. But undoing paint needs more than an opposite amount. For example, painting either blue or green red produces the same result, hiding which earlier color to restore. I think the mistake is assuming every edit has a unique opposite. Where do those earlier values come from? The shape saves a snapshot, meaning its values at a particular time. Its save method returns a pair containing position and color, and restore writes that pair back.

5:32 Our history doesn't need to read the saved position and color separately. It keeps the command, which calls the shape's own restore method. Memento is the pattern where the edited object saves and restores its own state. State means the values we're keeping. Other code can read this saved pair. A fuller Memento design can prevent that, but our example only keeps save and restore with the shape. Now take a fresh blue shape at 10. Create a request to paint it red, but leave that request waiting. Its saved value is None, meaning no pair has been saved yet.

6:07 While paint waits, run the movement first and reach 15. Saving when we created the paint request would have kept the old position 10. Which is why execute saves immediately before painting. The two lines capture 15 and blue, then replace the color with red. That stops Undo Paint from also undoing the earlier move. The change we're reversing began at 15, even though the request had been waiting since 10. Follow restore back into the shape. Undoing paint gives 15 and blue; redoing it saves that current pair and paints red again.

6:39 For a newly requested edit, create a separate command object. Controlled redo reuses its recorded command, so we don't replace one action's saved information while creating another. We can now recover an overwritten color. The next check is whether the thing we saved actually stays independent while the live shape changes. Now compare saving values with keeping another reference to the shape. Would that preserve its earlier position and color? No. An alias is a second name pointing to the existing object.

7:09 Both arrows reach that one live shape; the snapshot card holds the earlier values separately. Move and paint the shape, and both names now see 15 and red. The saved values still say 10 and blue. Restoring that pair changes the existing shape. It doesn't create a replacement shape, so the alias also sees 10 and blue again. We've saved a whole number and text. Our move replaces the position value in the shape; it doesn't rewrite the old number in the saved pair. That doesn't promise an independent copy of other objects we might save.

7:44 I'm more worried about how much we restore. If Paint saved the position too, could undoing a color change erase a later movement? Consider this separate case. Record paint red at position 10, then move plus 7 outside history. The live shape reaches 17, but paint saved 10 and blue. Undo Paint writes that whole pair back, so the unrecorded movement disappears too. We asked for the earlier color, and it gave us the earlier position too. Our normal editor's rule is that one history owner records every edit.

8:16 The outside move deliberately broke that rule. Saving the entire shape can therefore restore too much if another path changes it. Choosing what to save and which changes history owns belongs in the design. That lets us undo edits recorded by this history. It still can't tell whether two requests mean one intended move. Now test that limit with duplicate submissions. Suppose a caller sends one intended movement twice, using two fresh plus 5 commands. The first reaches 15. The second takes 15 to 20, and Done now holds two entries.

8:49 History received two different command objects, even though the caller intended one move. I was treating a fresh object as a fresh user action. That assumption fails as soon as the caller repeats a submission. Yep. What does pressing Undo once do with those two recorded entries? It reverses only the latest movement, leaving 15. One entry remains in Done, and the reversed entry sits in Undone. A retry is another attempt after an uncertain result. An external service is another program we send requests to.

9:22 It might make the change even if its response never reaches us. Creating another command gives us something to send again, but no evidence about the first attempt's effect. How could the service tell a retry from a new action? Some services recognize a label reused for the same intended action. Under their documented conditions, repeating that action won't add its effect again. That's called idempotency. The service has to recognize the repeated intention and apply its promised rule. A label that it ignores is just more text in our request.

9:55 Check the called service's actual promise, because our local history can't supply it. Nor can we treat Undo in this editor as reversing a change already made elsewhere. We know the arithmetic of this shape, not the outcome behind that service boundary. I'd start with the stored function when all we need is run later. Use an action object when keeping its information and reversal behavior together helps. Save earlier values when an edit destroys information, and make the history's ownership explicit.

10:24 Repeating an external action needs the service's documented repeat rules. Thanks for listening to Learning Podcasts.