Bird
Raised Fist0

What is the main issue causing infinite recursion when calling cost() on a decorated object?

medium🐞 Bug Identification Q7 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
Examine the following decorator implementation. What is the main issue causing infinite recursion when calling cost() on a decorated object? ```python class CoffeeDecorator: def __init__(self, coffee): self._coffee = coffee def cost(self): return self.cost() + 1 ```
AThe cost method should not add 1 to the result.
BThe decorator does not initialize the wrapped object properly.
CThe method calls itself recursively instead of delegating to the wrapped object.
DThe decorator class is missing a description method.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the recursive call

    The cost() method calls self.cost(), which calls itself infinitely.
  2. Step 2: Correct approach

    It should call self._coffee.cost() to delegate to the wrapped object.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Recursive call without base case causes infinite recursion [OK]
Quick Trick: Decorator must delegate to wrapped object, not call itself [OK]
Common Mistakes:
MISTAKES
  • Assuming initialization error instead of recursion.
  • Thinking adding 1 is wrong rather than the recursion.
  • Confusing missing methods with recursion issue.
Trap Explanation:
PITFALL
  • Calling self.cost() causes infinite recursion instead of delegating to wrapped object.
Interviewer Note:
CONTEXT
  • Tests ability to spot common implementation errors in decorators.
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