Bird
Raised Fist0

Review the following Invoker method snippet for executing commands with undo/redo support. Identify the bug that causes the redo stack to not clear correctly after a new command execution.

medium🐛 Buggy Code Q7 of Q15
OOP & Design Patterns - Command Pattern - Undo/Redo, Request Queuing & Logging
Review the following Invoker method snippet for executing commands with undo/redo support. Identify the bug that causes the redo stack to not clear correctly after a new command execution.

def execute_command(self, command):
    command.execute()
    self.undo_stack.append(command)
    # Missing line here?
AExecuting the command twice accidentally
BNot appending the command to the undo stack
CFailing to clear the redo stack after executing a new command
DClearing the undo stack instead of the redo stack
Step-by-Step Solution
Solution:
  1. Step 1: Understand redo stack behavior

    Redo stack should be cleared when a new command is executed to prevent invalid redo states.
  2. Step 2: Analyze the code snippet

    The snippet executes the command and pushes it onto the undo stack but does not clear the redo stack.
  3. Final Answer:

    Failing to clear the redo stack after executing a new command -> Option C
  4. Quick Check:

    Redo stack must reset on new commands [OK]
Quick Trick: Redo stack clears on new commands to avoid stale redo [OK]
Common Mistakes:
MISTAKES
  • Thinking redo stack should never be cleared
  • Confusing undo and redo stack roles
  • Assuming command execution automatically clears redo stack
Trap Explanation:
PITFALL
  • Option B looks plausible but the undo stack is correctly appended; the bug is redo stack not cleared.
Interviewer Note:
CONTEXT
  • Tests ability to identify subtle bugs in undo/redo command invoker implementations.
Master "Command Pattern - Undo/Redo, Request Queuing & Logging" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes