Bird
0
0

Identify the bug in this undo implementation of a Command pattern:

medium📝 Analysis Q14 of 15
LLD - Design — Tic-Tac-Toe Game
Identify the bug in this undo implementation of a Command pattern:
class MultiplyCommand:
    def __init__(self, value, receiver):
        self.value = value
        self.receiver = receiver
        self.prev = None
    def execute(self):
        self.prev = self.receiver.total
        self.receiver.total *= self.value
    def undo(self):
        self.receiver.total /= self.value

receiver = type('Receiver', (), {'total': 10})()
cmd = MultiplyCommand(2, receiver)
cmd.execute()
cmd.undo()
print(receiver.total)
AExecute should add instead of multiply
BUndo method is missing
CUndo should restore previous value, not divide
DReceiver class is not defined
Step-by-Step Solution
Solution:
  1. Step 1: Analyze execute and undo methods

    Execute saves previous total and multiplies current total by value. Undo divides total by value.
  2. Step 2: Identify problem with undo

    Undo divides by value, but if value is zero or changed, this may not restore original total exactly. It should restore saved previous total instead.
  3. Final Answer:

    Undo should restore previous value, not divide -> Option C
  4. Quick Check:

    Undo must restore saved state, not recalculate [OK]
Quick Trick: Undo must restore saved state, not recalculate [OK]
Common Mistakes:
MISTAKES
  • Assuming division always reverses multiplication
  • Not saving previous state before execute
  • Ignoring edge cases like zero multiplication

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes