05 / 11

How do you design an Undo/Redo functionality? (Command Pattern)

Difficulty: 4/10

Undo and Redo with the Command Pattern

I would represent each user operation as a Command containing the information required to execute and undo that operation. The application maintains an undo stack and a redo stack. Executing a new command pushes it onto the undo stack and clears the redo stack. Undo moves the command to the redo stack, while redo executes it again.

javascript
  1. 1

    Command encapsulates an action and its inverse operation.

  2. 2

    Undo and redo stacks maintain operation history.

  3. 3

    A new command normally invalidates the redo history.

  4. 4

    For complex applications, commands may need snapshots, event sourcing, or compensating operations.

  5. 5

    Commands should consider transaction boundaries and failure handling.

Follow-up Questions

  • How would you implement undo for a database transaction?
  • When would snapshots be better than inverse commands?
  • How would you limit command history memory?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.