Bird
0
0

In the following code snippet, what is the main issue that breaks the Memento pattern?

medium📝 Analysis Q14 of 15
LLD - Behavioral Design Patterns — Part 2
In the following code snippet, what is the main issue that breaks the Memento pattern?
class Originator:
    def __init__(self):
        self._state = ""
    def set_state(self, state):
        self._state = state
    def save(self):
        return self._state  # returns state directly
    def restore(self, memento):
        self._state = memento

originator = Originator()
originator.set_state("State1")
memento = originator.save()
originator.set_state("State2")
originator.restore(memento)
print(originator._state)
AThe save method returns state directly, exposing internal details
BThe restore method does not update the state
CThe Originator class lacks a Memento class
DThe set_state method is missing
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the save method

    The save method returns the internal state directly instead of encapsulating it in a Memento object, exposing internal details.
  2. Step 2: Understand Memento pattern principle

    The pattern requires hiding the internal state inside a Memento object to prevent external access. Returning raw state breaks encapsulation.
  3. Final Answer:

    The save method returns state directly, exposing internal details -> Option A
  4. Quick Check:

    Save must hide state in Memento [OK]
Quick Trick: Save must return Memento, not raw state [OK]
Common Mistakes:
MISTAKES
  • Thinking restore method is faulty
  • Believing Memento class is mandatory in code
  • Ignoring encapsulation principle

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes