Command
medium 50 minA command wraps a request in an object: what to do, with which receiver and parameters.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Wishes as objects: who holds them, who runs them, what they remember.
Operations
Remote and lamp
Full, off, undo, undo, redo. Follow the field before.
Step 1 of 8
Ready
The lamp is dark. The remote has recipes for full and off. The commands shown faded do not exist yet.
Step 1: Ready
class SetLevel: def execute(self): self.before = self.light.level self.light.set_level(self.level) def undo(self): self.light.set_level(self.before)class Remote: def press(self, slot): self.run(self.slots[slot]()) def run(self, command): command.execute() self.done.append(command) self.undone.clear() def undo(self): command = self.done.pop() command.undo() self.undone.append(command) def redo(self): command = self.undone.pop() command.execute() self.done.append(command)- Watch
- before
- Result
- Exact undo
The remote never calls the lamp.
In the real world
The same command doing real jobs. Pick one and step through it.
A slot that holds a command instead of a recipe.
Step 1 of 3
First press
Level 100 becomes 50, before is 100.
Step 1: First press
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Undo by the opposite
criticalThe state before is not always the opposite.
Wrongdef undo(self): self.light.set_level(0)Rightdef undo(self): self.light.set_level(self.before)Reading the old value too early
criticalOthers may change it between making and running.
Wrongdef __init__(self, light, level): self.before = light.levelRightdef execute(self): self.before = self.light.level self.light.set_level(self.level)Redo not cleared
criticalRedo applies a command to a state it was not made for.
Wrongdef run(self, c): c.execute() self.done.append(c)Rightdef run(self, c): c.execute() self.done.append(c) self.undone.clear()Remember before running
majorIf execute raises, the history holds something that never happened.
Wrongself.done.append(c)c.execute()Rightc.execute()self.done.append(c)Macro undo in forward order
majorTwo parts on one lamp end at the wrong level.
Wrongfor c in self.commands: c.undo()Rightfor c in reversed(self.commands): c.undo()Redo through run
majorrun clears the undone stack, so the second redo finds nothing.
Wrongdef redo(self): self.run(self.undone.pop())Rightdef redo(self): c = self.undone.pop() c.execute() self.done.append(c)
Interview tips
Find the missing arrow
- Invoker knows commands.
- Commands know receivers.
- Never invoker to receiver.
Exact undo
- Read in execute.
- Restore, do not invert.
- Start tests from 30, not 0.
Recipes
- A slot makes commands.
- One press, one object.
- One object, one memory.
Outside the process
- Id from the sender.
- Acknowledge last.
- Kinds in a map.
Know when not
- One operation: a function.
- No undo, queue or log: a call.
- Facts: an event.