Bird
Raised Fist0

Which of the following design changes best exemplifies adherence to the Open/Closed Principle when adding a new discount strategy to an e-commerce system?

easy🔍 Pattern Recognition Q2 of Q15
OOP & Design Patterns - Open/Closed Principle - Open for Extension, Closed for Modification
Which of the following design changes best exemplifies adherence to the Open/Closed Principle when adding a new discount strategy to an e-commerce system?
AAdd a new method in the existing DiscountCalculator class for the new discount.
BUpdate the DiscountCalculator class to handle the new discount type explicitly.
CModify the existing discount calculation method to include a new conditional branch.
DCreate a new class implementing a DiscountStrategy interface for the new discount.
Step-by-Step Solution
Solution:
  1. Step 1: Understand OCP in discount strategies

    OCP encourages adding new functionality by extension, not by modifying existing code.
  2. Step 2: Evaluate options

    Add a new method in the existing DiscountCalculator class for the new discount and Update the DiscountCalculator class to handle the new discount type explicitly both modify existing classes, violating OCP. Modify the existing discount calculation method to include a new conditional branch adds conditionals, also violating OCP. Create a new class implementing a DiscountStrategy interface for the new discount introduces a new class implementing a common interface, extending behavior without modification.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    New discount added via new class, no existing code changed [OK]
Quick Trick: New features via new classes implementing interfaces, not modifying existing code [OK]
Common Mistakes:
MISTAKES
  • Thinking adding methods or conditionals is extension
  • Confusing modification with extension
Trap Explanation:
PITFALL
  • Candidates often think adding methods or conditionals is extending, but it modifies existing code, breaking OCP.
Interviewer Note:
CONTEXT
  • Checks understanding of extension vs modification in OCP context.
Master "Open/Closed Principle - Open for Extension, Closed for Modification" 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