Bird
0
0

Examine this Observer pattern code snippet. What is the issue with the notifyObservers method?

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

Examine this Observer pattern code snippet. What is the issue with the notifyObservers method?

class Subject:
    def __init__(self):
        self.observers = []
    def addObserver(self, observer):
        self.observers.append(observer)
    def notifyObservers(self):
        for observer in self.observers:
            observer.update()
AThe addObserver method should check for observer type before adding
BObservers are not stored in a set, so duplicates are allowed
CThe notifyObservers method does not pass the Subject state to observers
DIf an observer removes itself during update, it causes iteration errors
Step-by-Step Solution
Solution:
  1. Step 1: Analyze notifyObservers method

    It iterates over observers and calls update on each.
  2. Step 2: Identify potential issue

    If an observer removes itself during update, modifying the list during iteration causes runtime errors.
  3. Step 3: Evaluate other options

    While B, C, and D could be improvements, the critical bug is the unsafe iteration.
  4. Final Answer:

    If an observer removes itself during update, it causes iteration errors -> Option D
  5. Quick Check:

    Modifying list during iteration causes errors [OK]
Quick Trick: Avoid modifying observer list during notification [OK]
Common Mistakes:
MISTAKES
  • Ignoring concurrent modification during iteration
  • Assuming notify passes state automatically
  • Not considering duplicate observers as critical bug

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes