LogRocket Blog

SOLID series: The Open-Closed Principle

thumbnail

Overview of the Open-Closed Principle

What does “open for extension, closed for modification” mean in OCP?

The Open-Closed Principle (OCP) states that modules should be open to extension, allowing new modules or classes to interact with the existing system without modifying it, while being closed to modification, meaning the existing source code remains unchanged.

Extension vs. modification

Extension involves adding new code, such as new subclasses or interfaces, to the existing system without altering it. Modification, on the other hand, involves changing the existing source code.

Critics of OCP

Critics argue that strict adherence to the OCP can lead to convoluted code structures, especially when overused or misapplied.

Interpretations of the Open-Closed Principle

Meyer’s Open-Closed Principle

Bertrand Meyer, in his 1988 book "Object-Oriented Software Construction," introduced the concept of the Open-Closed Principle. He defined a module as open if it allows for extension by adding new functions and fields, and closed if it has a stable interface for use by other modules.

Polymorphic Open-Closed Principle

In the 1990s, the Open-Closed Principle was reinterpreted to emphasize the importance of polymorphism and inheritance to achieve openness for extension and closure for modification.

Application of the Open-Closed Principle

Scalable applications

Large-scale systems benefit greatly from the Open-Closed Principle, as it allows for easy extension of modules without modifying existing functionality, enabling the seamless addition of new features and components.

API design

APIs can evolve effectively when the Open-Closed Principle is applied, enabling the creation of flexible and extensible interfaces that can accommodate future changes and enhancements.

Straying from OCP

It is important to consider the context and scale of a project when deciding whether to strictly adhere to the Open-Closed Principle, as overusing it in certain scenarios can lead to overly complex code structures and hinder maintainability.