Bird
Raised Fist0

Identify the bug in the following decorator implementation that causes incorrect behavior when stacking decorators:

medium🐞 Bug Identification Q14 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
Identify the bug in the following decorator implementation that causes incorrect behavior when stacking decorators:
ALine 5: Recursive call to self.cost() instead of super().cost() causes infinite recursion
BLine 6: Incorrect string formatting in description
CLine 2: Incorrect call to super().__init__
DLine 4: Missing amount parameter default value
Step-by-Step Solution
  1. Step 1: Analyze cost() method

    cost() calls self.cost() recursively, causing infinite recursion instead of delegating to wrapped object.
  2. Step 2: Identify correct delegation

    Should call super().cost() to delegate to wrapped coffee object's cost method.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Recursive call causes stack overflow, breaking decorator chain [OK]
Quick Trick: Decorator methods must delegate via super(), not self [OK]
Common Mistakes:
MISTAKES
  • Calling self.cost() instead of super().cost() in decorators
  • Forgetting to delegate calls properly
Trap Explanation:
PITFALL
  • Calling self.cost() looks like recursion but is a subtle bug causing infinite loops.
Interviewer Note:
CONTEXT
  • Tests attention to delegation details in decorator implementations.
Master "Decorator Pattern - Wrapping Behaviour Without Subclassing" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes