Supporting Change Without Breaking Software
As part of the S.O.L.I.D. design principles, the Open–Closed Principle (OCP) ensures parts of software (classes) are open for extension, but closed for modification.
In other words, you should be able to modify a class’ behavior without modifying its code.
New methods are added by adding new classes without changing current code.
Also, since new functionality is added without disturbing other parts of the system, you only need test the new code.
This principle leverage the use of the Single Responsibility Principle (SRP) in that it isolates the interface to a single responsibility, thus avoiding the need for future changes since each class should have only one responsibility.
Practically, this principle is implemented by adding new functionality to derived classes while requiring users to access class through an interface as demonstrated below.
I’ll begin with the same Employee class as the SRP article.
A new requirement was added (common to software projects) when calling to report whether or not an employee has a family when out on vacation.
Usually during software development, change requests necessitate changing existing code. For example, I would add a hasFamily attribute and update TakeVacation() to use it to report during that behavior whether or not they have a family. However, I would then need to change the code instantiating its objects and doing so presents unpredictable errors, especially in a team environment, with ongoing changes to the system.
Instead of chancing putting the application into a unstable state, I’ll use OCP to incorporate the change without affecting the working and tested parts of the system.
As demonstrated in the SRP article, I’ll begin by creating a contract between functionality and its users, except instead of an interface, I’ll create an abstract class, which as a similar interface by codifying behavior other classes must implement, or provide its details.
Note: To add new functionality to employee objects (or in the future), I didn’t and won’t need to change the existing abstract (template) Employee class, I simply create new class to derive the abstract class’ behavior, then instantiate objects of that new derived type, using the abstract class to define the variable. Also, I won’t have to change existing code using previous classes to support changes.