Bird
Raised Fist0

Identify the bug in the following code snippet implementing the strategy pattern for payment processing:

medium🐞 Bug Identification Q14 of Q15
OOP & Design Patterns - Strategy Pattern - Replace Conditionals with Polymorphism
Identify the bug in the following code snippet implementing the strategy pattern for payment processing:
class PaymentProcessor:
    def __init__(self, strategy: PaymentStrategy):
        self.strategy = strategy

    def pay(self, amount):
        if isinstance(self.strategy, CreditCardStrategy):
            print(f"Processing credit card payment of ${amount}")
        elif isinstance(self.strategy, UPIStrategy):
            print(f"Processing UPI payment of ${amount}")
        else:
            print("Invalid payment method")
AThe bug is that the pay method uses conditional checks instead of polymorphism.
BThe bug is missing a call to the strategy's pay method inside pay().
CThe bug is in the constructor where the strategy is not assigned properly.
DThe bug is that the else clause should raise an exception instead of printing.
Step-by-Step Solution
  1. Step 1: Analyze the pay method implementation

    The pay method uses isinstance checks and conditionals to decide behavior, which defeats the purpose of polymorphism.
  2. Step 2: Identify correct polymorphic usage

    The correct approach is to call self.strategy.pay(amount) directly, letting each strategy handle its own payment logic.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Using conditionals in pay() breaks the strategy pattern [OK]
Quick Trick: Strategy pattern requires polymorphic calls, not conditionals [OK]
Common Mistakes:
MISTAKES
  • Using type checks instead of polymorphism
Trap Explanation:
PITFALL
  • Code looks correct but violates open-closed principle and polymorphism.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to spot subtle misuse of design patterns.
Master "Strategy Pattern - Replace Conditionals with Polymorphism" 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