Open/Closed Principle
Updated 2026-07-30
Summary
In the field of object-oriented programming, the Open/Closed Principle (OCP) states that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification," meaning an entity is allowed to change its behavior without altering its source code. This feature is particularly valuable in production environments where changing source code requires code reviews, unit tests, and similar processes to ensure product quality. Code that follows this principle does not change when extended, thus avoiding these processes. The naming of the Open/Closed Principle is applied in two ways. Both use inheritance to resolve the apparent dilemma, but their purposes, techniques, and results are different.
Definition
Software entities (classes, modules, functions) should be open for extension but closed for modification. That is, new functionality is introduced by adding new code without modifying existing code. Scaffold use: Architecture that embraces change. When designing rules or processes, reserve "plugin interfaces." When new situations arise, there is no need to start over (modification); just plug in a new plugin (extension).
Introduction
How to use
Architecture that embraces change. When designing rules or processes, reserve "plugin interfaces." When new situations arise, there is no need to start over (modification); just plug in a new plugin (extension).
Mechanism
The Open/Closed Principle (OCP) requires that software entities be open for extension and closed for modification: new behaviors should be added through extension rather than by altering existing code, thereby reducing regression risk and improving stability.
Practice
In progress 0/4Practice this model in one real situation:
Cases
- Use the strategy pattern to add new algorithms without changing the original class; plugin architecture supports extension.
Common pitfalls
- Over-abstraction leads to class explosion; pre-building unnecessary complexity for 'possible changes'.
Sources
Source support: Explicit
References currently contain only Wikipedia links; primary sources still need review.
- zh.wikipedia.orghttps://zh.wikipedia.org/wiki/%E5%BC%80%E9%97%AD%E5%8E%9F%E5%88%99verified
account_treeGenealogyexpand_more
PRIVATE NOTES · Only visible to you
SAVED Q&A
ENTRY Q&A · Private saving available
Ask with a clear boundary
thinkingmodels answers from published entry context only.
Your question is sent to thinkingmodels. The answer uses public entry context only.
RELATED MODELS