This is the ‘O’ in SOLID
“The Open / Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” – Wikipedia
- Open to extension is to allow new behavior to be added in the future
- Closed to modification is not to change the source/binary code
An example from Steve Smith that really cleared things up for me was a ‘Price Calculator’ routine on a shopping cart order item. The logic to calculate the costs was abstracted so the core class was not modified but rather extended when new price rules were applied.
These rules would be logic that business dreams up:
- If the cost is based on “each”, then the rule is quantity * cost
- If the is based on “weight”, then the rule is qty * cost / 1000 (As its in grams, we need per KG)
- Other rules such as a “special”
How do we open things for extension?
The key is to rely on abstractions, so this is interfaces or an abstract base class. Its however very important not to simply apply OCP to every class unless you know based on the problem domain that your code is solving that the business rules are likely to change.
Steve often speaks of “Refactoring to a better design”, this means you should write your code with the least amount of complexity first and when needed refactor it and apply a principal such as OCP. So if it changes once, accept it. If it changes again consider refactoring.
- Existing core classes are not changed so you are less likely to introduce regression bugs
- You are adding new classes each time, so you can test and have faith you will not upset things
- This add complexity and must be used with caution, dont use OCP to try impress your boss