Bird
Raised Fist0

What is the best strategy to refactor it to comply with OCP without breaking existing functionality?

hard🎤 Interviewer Follow-up Q15 of Q15
OOP & Design Patterns - Open/Closed Principle - Open for Extension, Closed for Modification
Suppose you have a legacy system that violates the Open/Closed Principle by frequently modifying core classes for new features. What is the best strategy to refactor it to comply with OCP without breaking existing functionality?
AReplace all core classes with interfaces and rewrite all implementations from scratch
BUse global variables to control behavior changes instead of modifying classes
CContinue modifying core classes but add feature flags to isolate changes
DIntroduce abstract base classes or interfaces and create new subclasses for new features, leaving existing classes unchanged
Step-by-Step Solution
  1. Step 1: Understand refactoring goals

    Refactor to enable extension via new subclasses without modifying existing tested classes.
  2. Step 2: Why introducing abstract base classes or interfaces and creating new subclasses for new features, leaving existing classes unchanged fits

    Introducing abstractions and subclassing allows adding features by extension, preserving existing code.
  3. Step 3: Why other options fail

    Replace all core classes with interfaces and rewrite all implementations from scratch is costly and risky; Continue modifying core classes but add feature flags to isolate changes continues violating OCP; Use global variables to control behavior changes instead of modifying classes introduces global state, increasing complexity and bugs.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Refactor by abstraction and extension, not rewrite or global state hacks.
Quick Trick: Refactor with abstractions and subclasses, keep existing code intact [OK]
Common Mistakes:
MISTAKES
  • Thinking rewrite is the only way to comply with OCP
  • Believing feature flags solve OCP violations
  • Using global variables as a workaround
Trap Explanation:
PITFALL
  • Option A is impractical; C and D ignore OCP principles; B aligns with best refactoring practices.
Interviewer Note:
CONTEXT
  • Evaluates candidate's ability to apply OCP in legacy code refactoring scenarios.
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