Bird
Raised Fist0

Which design approach best fits this requirement and why?

hard🌍 Real-world Scenario Q9 of Q15
OOP & Design Patterns - Composition vs Inheritance - Favour Composition, Why & When
You are designing a payment processing system that must support multiple payment methods (credit card, PayPal, crypto) and allow adding new methods without changing existing code. Which design approach best fits this requirement and why?
AUse inheritance with a PaymentMethod base class and subclasses for each method.
BUse composition with a PaymentProcessor class that delegates to payment strategy objects.
CUse static utility classes for each payment method to avoid object overhead.
DUse global configuration flags to switch payment method behaviors.
Step-by-Step Solution
Solution:
  1. Step 1: Identify need for open-closed principle

    System must be open for extension but closed for modification.
  2. Step 2: Evaluate inheritance approach

    Adding new subclasses requires modifying or recompiling base code, violating open-closed principle.
  3. Step 3: Composition with strategy pattern

    Delegating to payment strategy objects allows adding new methods without changing existing code.
  4. Step 4: Assess other options

    Static utilities and global flags reduce extensibility and increase coupling.
  5. Final Answer:

    Option B -> Option B
  6. Quick Check:

    Composition with delegation supports extensibility without code changes [OK]
Quick Trick: Composition supports open-closed principle better than inheritance [OK]
Common Mistakes:
MISTAKES
  • Assuming inheritance is always best for code reuse
  • Using static methods reduces extensibility
Trap Explanation:
PITFALL
  • Candidates often pick inheritance for reuse, missing extensibility and maintainability issues.
Interviewer Note:
CONTEXT
  • Evaluates real-world application of composition for extensible design.
Master "Composition vs Inheritance - Favour Composition, Why & When" 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