Bird
0
0

Identify the bug in this Observer pattern implementation:

medium📝 Analysis Q14 of 15
LLD - Behavioral Design Patterns — Part 1

Identify the bug in this Observer pattern implementation:

class Subject:
    def __init__(self):
        self.observers = set()
    def attach(self, observer):
        self.observers.add(observer)
    def notify(self):
        for obs in self.observers:
            obs.update()

class Observer:
    def update(self, state):
        print(f"State updated to {state}")

subject = Subject()
obs = Observer()
subject.attach(obs)
subject.notify()
AObserver.update requires a state argument but notify calls without it
BSubject.observers should be a list, not a set
Cattach method should remove observers, not add
Dnotify method should not call update
Step-by-Step Solution
Solution:
  1. Step 1: Check method signatures and calls

    The Observer's update method expects a state argument, but notify calls update() without any argument.
  2. Step 2: Identify mismatch causing error

    This mismatch will cause a runtime error due to missing required positional argument.
  3. Final Answer:

    Observer.update requires a state argument but notify calls without it -> Option A
  4. Quick Check:

    Method argument mismatch causes error [OK]
Quick Trick: Check method parameters match calls exactly [OK]
Common Mistakes:
MISTAKES
  • Ignoring missing argument errors
  • Thinking sets are invalid for observers
  • Misunderstanding attach method purpose

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes