Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Classes should be open for extension, but closed for modification.
The Open Closed Principle (OCP) is undoubtedly the most important of all the SOLID principles. In fact, each of the remaining class principles are derived from OCP. It originated from the work of Bertrand Meyer, who is recognized as an authority on the object-oriented paradigm. OCP states that we should have the ability to add new features to our system without having to modify our set of preexisting classes. As stated previously, one of the benefits of the object-oriented paradigm is to enable us to add new data structures to our system without having to modify the existing system’s code base.
Let’s look at an example to see how this can be done. Consider a financial institution where we have to accommodate different types of accounts to which individuals can make deposits. Figure A.1 shows a class diagram that illustrates how we might structure a portion of our system. (For the purposes of this discussion, we focus on how the OCP can be used to extend the system.)