Bird
Raised Fist0

Which modification best supports this requirement while maintaining clean design?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Strategy Pattern - Replace Conditionals with Polymorphism
Suppose you want to extend the payment system to allow switching payment strategies at runtime based on user input, including invalid or unsupported methods. Which modification best supports this requirement while maintaining clean design?
AUse a factory method to get the strategy instance and inject it into PaymentProcessor; handle invalid methods by raising exceptions.
BKeep the strategy selection logic inside the PaymentProcessor's pay method with if-else chains.
CHardcode all payment methods inside PaymentProcessor and add a default fallback strategy for invalid inputs.
DRemove the strategy interface and implement all payment methods inside PaymentProcessor with switch-case.
Step-by-Step Solution
  1. Step 1: Understand runtime strategy switching

    Switching strategies at runtime requires decoupling strategy selection from the context and handling invalid inputs gracefully.
  2. Step 2: Identify design that supports clean extensibility and error handling

    Using a factory method to create strategy instances and injecting them into PaymentProcessor allows runtime flexibility and clean error handling via exceptions.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Factory + DI + exceptions enable runtime switching and robustness [OK]
Quick Trick: Factory and DI enable runtime strategy switching with error handling [OK]
Common Mistakes:
MISTAKES
  • Hardcoding strategies or using conditionals inside context
Trap Explanation:
PITFALL
  • Naive solutions keep conditionals inside context, breaking open-closed principle and flexibility.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to adapt design patterns for runtime flexibility and robustness.
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