Bird
Raised Fist0

In the following code snippet implementing the Chain of Responsibility pattern, what is the error?

medium📝 Analysis Q14 of Q15
LLD - Behavioral Design Patterns — Part 1
In the following code snippet implementing the Chain of Responsibility pattern, what is the error?
class Handler:
    def __init__(self, successor=None):
        self.successor = successor
    def handle(self, request):
        if self.can_handle(request):
            print(f"Handled {request}")
        else:
            self.successor.handle(request)
    def can_handle(self, request):
        return False

h1 = Handler()
h2 = Handler(h1)
h2.handle("Request")
Ahandle method does not print anything
Bcan_handle method is missing
CSuccessor is assigned incorrectly
DCalling handle on None successor causes error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze successor chain

    h2's successor is h1, h1's successor is None by default.
  2. Step 2: Trace handle calls

    Neither handler can handle the request, so h2 calls h1.handle, then h1 calls self.successor.handle which is None.handle causing an error.
  3. Final Answer:

    Calling handle on None successor causes error -> Option D
  4. Quick Check:

    None successor leads to AttributeError [OK]
Quick Trick: Check if successor is None before calling handle [OK]
Common Mistakes:
MISTAKES
  • Ignoring None successor causing crash
  • Assuming can_handle is missing
  • Thinking print is missing output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes