SOLID Part 2March 06, 2012 -
Ivar Jacobson once said
All systems change during their life cycles. This must be borne in mind when developing systems expected to last longer than the first version.
This is why we want to try to architect our projects in such a way that the future doesn’t become ever so painful. The principle I’ll discuss in this article helps to make that a reality. Back about 2 years after I was born, Bertrand Meyer described the principle when he stated
"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
Another way to state the principle is that your classes, modules, and functions should be written in such a way that future changes can be accomidated by extending existing code with new code instead of rewriting the original code. If the existing code in a class works and you don’t need to modify it to accomidate the new changes that need to happen, that existing code still works. This also means any code depending on that class still works. This ideal situation is a win for everyone. QA doesn’t have to roll their eyes and file regression bugs (and by QA I mean you if you’re a one-man shop), product managers don’t suffer from the nervousness that stems from changes in code resulting in broken issues elsewhere, programmers can enjoy writing new code instead of figure out what broke, smooth sailing for all.
This is probably one of the hardest to implement of the SOLID principles. It’s not really possible to close your code from all possible changes while still making it flexible enough to handle whatever your next client meeting comes up with. The more experience you gain however, the easier it can be to predict the kinds of ways your code might need to change and make plans accordingly. Some common changes I have encountered includes
- "Maybe this list will need to be in a different order"
- "Maybe request URLs will need to change in this HTTP requester"
- "Maybe the routing style/method/order will need to change in this HTTP server"
- "Maybe these UI elements will need to also be used on the iPad"
The list goes on, but you get the idea.
Another part of this principle is that modules should depend on less-volatile modules. If code changes in a module your code depends on, that means your code needs to change too. This would violate the Open/Closed principle. It’s not a hard law and all, but you definitely save yourself headache the more you’re able to adhere to this principle.