Bird
0
0
LLDsystem_design~7 mins

Command pattern for undo in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When users perform actions in an application, mistakes happen and they want to revert changes. Without a structured way to track and reverse operations, undoing actions becomes error-prone, inconsistent, or impossible, leading to poor user experience and potential data loss.
Solution
The command pattern encapsulates each user action as an object with methods to execute and undo the action. By storing these command objects in a history stack, the system can call undo on the last executed command to revert its effect, enabling reliable and consistent undo functionality.
Architecture
Client
Command

This diagram shows the client triggering commands that execute actions on receivers. Each command is stored in a history stack to support undo by calling undo() on the last command.

Trade-offs
✓ Pros
Enables clean separation between action execution and undo logic.
Supports complex undo/redo by stacking command objects.
Makes adding new commands easier without changing existing code.
Improves maintainability by encapsulating all action details.
✗ Cons
Increases memory usage due to storing command history.
Adds complexity by requiring command objects for every action.
Undo logic must be carefully implemented for each command to avoid inconsistent states.
Use when your application requires reliable undo/redo functionality with multiple reversible actions and you want to keep code modular and extensible.
Avoid if your system has very simple or stateless actions where undo is trivial or unnecessary, or if memory constraints prohibit storing command history.
Real World Examples
Adobe
Adobe Photoshop uses the command pattern to implement undo/redo for complex image editing operations, allowing users to revert changes step-by-step.
Microsoft
Microsoft Word applies the command pattern to track text editing commands, enabling users to undo and redo typing, formatting, and other document changes.
IntelliJ IDEA
IntelliJ IDEA uses the command pattern to manage undo/redo of code edits and refactorings, ensuring consistent state restoration.
Code Example
The before code shows a simple text editor without undo. The after code applies the command pattern by encapsulating write actions as commands with execute and undo methods. The editor keeps a history stack of commands to support undo by calling undo on the last command.
LLD
### Before: No command pattern, no undo support
class TextEditor:
    def __init__(self):
        self.text = ""

    def write(self, words):
        self.text += words

editor = TextEditor()
editor.write("Hello")
print(editor.text)  # Output: Hello


### After: Command pattern with undo support
class Command:
    def execute(self):
        pass
    def undo(self):
        pass

class WriteCommand(Command):
    def __init__(self, editor, words):
        self.editor = editor
        self.words = words

    def execute(self):
        self.editor.text += self.words

    def undo(self):
        self.editor.text = self.editor.text[:-len(self.words)]

class TextEditor:
    def __init__(self):
        self.text = ""
        self.history = []

    def execute_command(self, command):
        command.execute()
        self.history.append(command)

    def undo(self):
        if self.history:
            command = self.history.pop()
            command.undo()

editor = TextEditor()
cmd1 = WriteCommand(editor, "Hello")
editor.execute_command(cmd1)
print(editor.text)  # Output: Hello
editor.undo()
print(editor.text)  # Output: ""
OutputSuccess
Alternatives
Memento pattern
Stores snapshots of the entire object state rather than encapsulating actions as commands.
Use when: Choose when you need to restore entire object states and actions are hard to reverse individually.
Event sourcing
Stores all changes as a sequence of events that can be replayed to restore state, rather than individual command objects.
Use when: Choose when you want full audit trails and system state reconstruction from event logs.
Summary
The command pattern encapsulates actions as objects with execute and undo methods.
It enables reliable undo functionality by storing executed commands in a history stack.
This pattern improves code modularity and makes adding undo support easier and consistent.