The Open/Closed Principle

The open/closed principle (OCP) states that a module should be both open and closed (but with respect to different aspects). When designing a class, for instance, we should carefully encapsulate the implementation details, so that it has good maintenance, meaning that we want it to be open to extension but closed to modification.

What this means in simple terms is that, of course, we want our code to be extensible, to adapt to new requirements or changes in the domain problem. That means when something new appears on the domain problem, we only want to add new things to our model, not change anything existing that is closed to modification.

If for some reason, when something new has to be added we find ourselves modifying the code, then that logic is probably poorly designed. Ideally, when requirements change, we want to just have to extend the module with the new behavior, but without having to alter the current logic significantly.

This principle applies to several software abstractions. It could be a class or even a module we're talking about, but the idea remains the same. Let’s explore some examples.

Example of maintainability perils for not following the OCP

Let's begin with an example of a system that is designed in such a way that doesn't follow the OCP, in order to see the maintainability problems this carries, and the inflexibility of such a design.

The idea is that we have a part of the system that is in charge of identifying events as they occur in another system, which is being monitored. At each point, we want this component to identify the type of event, correctly, according to the values of the data that was previously gathered (for simplicity, we will assume it is packaged into a dictionary, and was previously retrieved through another means such as logs, queries, and many more). We have a class that, based on this data, will retrieve the event, which is another type with its own hierarchy.

From the class diagram below, we see an object that works with an interface (a base class, with several subclasses that can be used polymorphically):

Get hands-on with 1200+ tech skills courses.