Bird
0
0

Given the following code snippet, identify the bug that breaks the Chain of Responsibility pattern:

medium📝 Analysis Q14 of 15
LLD - Behavioral Design Patterns — Part 1
Given the following code snippet, identify the bug that breaks the Chain of Responsibility pattern:
class Handler:
    def __init__(self, successor=None):
        self.successor = successor
    def handle(self, request):
        if self.can_handle(request):
            return f"Handled {request}"
        else:
            return "Not handled"
    def can_handle(self, request):
        return False

class ConcreteHandler(Handler):
    def can_handle(self, request):
        return request == 'X'

chain = ConcreteHandler()
print(chain.handle('Y'))

What is the main issue here?
AThe successor is not initialized properly
BThe can_handle method always returns True
CThe handler does not pass the request to the successor
DThe handle method has a syntax error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the handle method logic

    The handle method checks can_handle; if False, it returns "Not handled" immediately without passing to successor.
  2. Step 2: Identify missing chain passing

    It should call self.successor.handle(request) if successor exists, but this is missing.
  3. Final Answer:

    The handler does not pass the request to the successor -> Option C
  4. Quick Check:

    Missing successor call breaks chain [OK]
Quick Trick: Always pass request to successor if not handled [OK]
Common Mistakes:
MISTAKES
  • Forgetting to call successor.handle()
  • Assuming can_handle always returns True
  • Ignoring successor initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes