Part 5 of 6 · 2 min read
Costs
When a lambda is enough.
Costs and alternatives
GoF lists the consequences. Command decouples the object that invokes an operation from the one that knows how to do it. Commands are first-class objects that can be stored and extended like any other. They can be grouped into composites. And new commands are easy to add, because no existing class changes.
The cost is a class for each operation. GoF also asks how smart a command should be. At one end it only binds a receiver to an action. At the other end it does all the work itself with no receiver. The first keeps logic in the receiver, where it can be reused. The second suits commands that stand alone.
In Java, a command with no undo is just a Runnable, and a lambda can stand for it: Runnable r = () -> schedule.add("09:00");. For many tasks that is all that is needed. Use full command classes when you need undo, logging, serialization, or a name and parameters you can inspect.
Command and Strategy look alike. A strategy is an algorithm that a context calls, and is chosen by the client. A command is a request, with its receiver and arguments already bound, that an invoker runs later.
Common mistake
Writing undo that assumes execute changed something. A command that did nothing must undo nothing, or it will destroy data that was there before.
Interview angle
Answer in your head first, then open it.
What is the Command pattern?
A request is wrapped as an object with execute, so it can be queued, logged, repeated and undone.
How do you implement undo and redo?
Each command stores what it needs to reverse itself. The invoker keeps an undo stack and a redo stack.
Where is it used?
Editors, button actions, job queues, transactions, and remote controls.
Check yourself: 1. What is a command with no undo in Java? 2. When should you use a full command class and not a lambda?
Words you will meet
| Word | Meaning |
|---|---|
| Command | A request wrapped as an object with an execute method |
| Receiver | The object that does the real work |
| Invoker | The object that asks a command to run |
| Undo stack | A list of commands that can be reversed, newest first |
| Macro command | A command made of several commands |