Free SOLID and design smells lessonsSOLID and design smells · Stage 0 · Change without pain · Step 2
Open for extension, closed for modification
How to add new behaviour by adding code instead of editing working code, and replacing type switches with polymorphism. About 13 minutes.
A method contains a long switch on an object's type, and a new type is added every few months. What is the usual refactoring?
- AIntroduce an interface and move each branch into a class for that type
- BAdd more cases to the switch carefully
- CReplace the switch with a series of boolean flags
Show the answer
Introduce an interface and move each branch into a class for that type. New types then arrive as new classes.
4 questions on this idea
Short questions that apply the idea to new cases: trace it, work out a number, put steps in order. A wrong answer explains itself.
Answer them in your browserFree account, no card. Your progress is saved, and the idea comes back in a quick review later.
Sign up free to solve