The full name of the Open Closed Principle is OCP. Softwareentities (modules, classes, functions, etc.) should be open forexrigidbut closed formodifcation. We translate this into Chinese: software entities (modules, classes, methods, etc.) should be “open for extension, closed for modification”.
Simply put, adding a new feature should extend the existing code (add modules, classes, methods, etc.), not modify the existing code (modify modules, classes, methods, etc.).
How to understand “Open for extensions, closed for modifications”
Adding new functionality should be done by extending the existing code (adding modules, classes, methods, properties, etc.) rather than modifying the existing code (modifying modules, classes, methods, properties, etc.). There are two things to note about this definition. The first point is that the open closed principle does not mean that changes are completely eliminated, but rather that new features are developed at the minimum cost of changing the code. Second, the same code change may be considered a “change” under coarse-code granularity. At a fine code granularity, it might be considered “extended.”
How to “Open for Extensions, Closed for Modifications”
We should always have the consciousness of expansion, abstraction and encapsulation. In writing the code, we should spend more time to think about, what this code possible future demand changes, how to design the code structure, keep good extension points in advance, to demand changes in the future, without changes to the code structure, minimize code changes, insert the new code and flexibly to the extension point.
However, even if we knew enough about the business and the system, it would be impossible to identify all of the extension points, and even if you could identify all of them, it would be unacceptably expensive to reserve extension points for all of them. We don’t have to overdesign for some distant, uncertain need to pay in advance.
It makes sense to do some extensibility design in advance when writing code for certain scenarios where extensions are likely to occur in the short term, or where changes in requirements have a significant impact on the code structure, or where the implementation cost is not high. However, for requirements that are uncertain to be supported in the future, or extension points that are complex to implement, we can wait until the requirements are driven and then refactor the code to support the extension requirements.
Many design principles, ideas, and patterns are designed to make code more extensible. In particular, most design patterns are summed up to solve the problem of code extensibility, and are guided by the open and closed principle. The most common approaches to code extensibility are polymorphism, dependency injection, interface-based programming rather than implementation, and most design patterns (e.g., decorators, policies, templates, chains of responsibility, and state).