How would you refactor a large if/else or switch statement that branches on a type string to follow the Open/Closed Principle?
Start by defining an interface that captures the one behavior every branch actually performs, such as a pay(double amount) method shared across every payment type. Then turn each branch of the if/else chain into its own class implementing that interface, moving the branch's logic directly into that class's method body. Finally, rewrite the original method so it takes the interface type as a parameter and simply delegates to it — for example, paymentMethod.pay(amount) — instead of inspecting a string and branching. After this refactor, adding a new case means writing one new class that implements the interface; the original dispatching method is never edited again, no matter how many new cases are added later.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response