Definition
The Open-Closed Principle (OCP) states that software entities (classes, modules, functions) should be open for extension but closed for modification. New behavior can be added by extending the entity (via inheritance, composition, or interfaces) without altering its existing source code.
Why It Matters
Violating OCP forces risky edits to tested, stable code every time requirements change, leading to regressions, increased testing burden, and fragile systems. Teams that master it ship new features by adding new code rather than editing old code, dramatically improving velocity, safety, and the ability to evolve large codebases over years without accumulating technical debt.
Core Concepts
- Open for Extension: The entity can be extended with new capabilities (new implementations, plugins, strategies) to satisfy new requirements.
- Closed for Modification: The core source of the entity does not need to be changed to accommodate those extensions.
- Abstraction as the Mechanism: Depend on abstractions (interfaces, abstract base classes, protocols) rather than concrete implementations. Concrete details are supplied later via dependency injection or configuration.
- Example in Python: Using
*args/**kwargsor protocol-based dispatch allows a function to accept an open-ended set of call signatures or types without modifying the function body for each new caller.