In general, it is more desirable to write new code in an existing codebase than it is to change existing code. This is especially true if you are unfamiliar with the codebase or it has little to no test coverage to facilitate ease of refactoring. Modifying an existing codebase increases the risk of breaking existing functionality and adds to the testing time as now we must regression test all parts of the system that have been affected by our change.
Wouldn’t it be nice if there were some way for us to modify existing functionality by writing new code, and leaving the existing codebase untouched (ok, relatively untouched)? Enter the Open/Closed Principle (OCP). The according to Hoyle definition states "software entities should be open for extension, but closed for modification". Sweet! But what does that mean?
It means we want to design our applications in such a way that allows us to add new functionality or behavior without having to modify existing code. This help us to reduce code fragility, where a single change causes a ripple throughout other areas of our application, forcing us to modify larger portions of existing code. Again, this increases our testing time and reduces the overall maintainability of the code.
So let’s look at a very simple example of how adhering to the Open/Closed Principle can help improve the value and quality of our code (I want to stay focused here on the OCP concept and not get bogged down in the fact that there are other design issues with this code, i.e., ignoring the Single Responsibility Principle) . Here is the ubiquitous person class:
We have a person class with two properties and one validation rule: the person must have a first name and it cannot be more than thirty characters. This works perfectly until the business rules change. Now we must add a new validation rule for the last name as well.
In order for us to change this code and apply the new business rules, we can either continue updating the IsValid property or take the time to update to code to fix this issue such that it will not burn us again.
First we will refactor our person class and introduce a validator class:
And here is the validator that picks up the new business rules: