Considerations for the Open-Closed Principle

Learn when it’s useful to ignore the open-closed principle.

Pros and cons of the open-closed principle

The open-closed principle is a useful thing to know, as it substantially minimizes the impact of any changes to our application code. If our software is designed with this principle in mind, then future modifications to any one of our code components won’t cause the need to modify any other components and assess the impact on any external applications.

However, unlike the single responsibility principle, which should be followed almost like a law, there are situations where applying the open-closed principle has more cons than pros. For example, when designing a component, we have to think of any potential changes to the requirements in the future. This, sometimes, is counterproductive, especially when our code is very likely to be radically restructured at some point.

So, while we still need to spend some time thinking about what new functionality might be added to our new class in the future, considering the most obvious changes is often sufficient.

While, strictly speaking, adding new public methods to the existing class without modifying the existing methods would violate the open-closed principle, it won’t cause the most common problems that the open-closed principle is designed to address. So, in most cases, it’s completely fine to do so instead of creating even more classes that expand our inheritance hierarchy.

Get hands-on with 1200+ tech skills courses.