
Classes, modules, and functions should be open for extension but closed for modification. In reality, software systems are constantly evolving and must adapt to new requirements. The question is: How should these adaptations be made? Should we modify existing structures directly. Ideally, no.
Instead, changes in a software system should be implemented by extending existing structures rather than modifying them at the source code level. Being “closed for modification” means minimizing changes to stable, tested code. But what does “open for extension” really mean? Essentially, it involves two main points:
- Separating the parts that are likely to change from the parts that remain stable in a clear and maintainable way.
- Leveraging abstractions (such as abstract classes or interfaces) to build flexible structures that can be extended with minimal impact on existing code.
The primary goals of the Open-Closed Principle (OCP) are to improve reusability and maintainability. While achieving a state of being completely “closed for modification” is practically impossible, striving for it leads to cleaner and more robust code.
Key Considerations
- Predicting the system’s evolution is critical. Components expected to change frequently should be designed for easy extension.
- Use abstraction and design patterns (like Strategy or Decorator) to introduce new functionality without altering the core logic.
Deep Dive
Below is an example using Swift that demonstrates OCP. In this case, we define a Shape
protocol and create concrete implementations for different shapes. Notice that adding a new shape (for example, a Triangle
) would not require modifying the existing function that calculates the total area.

In this example, if you need to add a new shape (such as a Triangle), you simply create a new class that conforms to the Shape
protocol. There is no need to alter the existing totalArea
function. This is a clear demonstration of the Open-Closed Principle in practice.
By writing code with OCP in mind, you ensure your software can adapt to new requirements with minimal disruption, leading to a more scalable and maintainable system overall.
Leave a Reply
You must be logged in to post a comment.