Modules should be open for enhancement but closed for modification.
Beware that wrong application of OCP may lead to the anti-pattern onion.
See also section contrary principles.
Bertrand Meyer: Object-Oriented Software Construction, p. 57pp.
Robert C. Martin created the SOLID principle collection where “SOLID” is an acronym for the following principles:
This is the subset of Martin's principles that deals with the design of classes. For the full list of principles he collected see Robert C. Martin's Principle Collection.
|Principles In "Object-Oriented Software Construction"|
|“Fife Rules”||Direct Mapping||Few Interfaces||Small Interfaces||Explicit Interfaces||Information Hiding|
|“Fife Principles”||Linguistic Modular Units||Self-Documentation Principle||Uniform Access Principle||Open-Closed Principle||Single Choice Principle|
|Further principles||Command-Query Separation||Symbolic Constant Principle||Taxomania Rule|
Let's say the high-level module (your business logic), wants to be able to add or remove clients to the database. Instead of it talking to the database directly, it defines an interface called ClientRepository which contains the methods the business logic needs (DIP). Now you go along and implement a MySQLClientRepository. Some time in the future, you are asked to switch to an oracle database. You can now, without modifying any code from your business logic, switch to the oracle database: by extending ClientRepository to implement OracleClientRepository. You just need to wire an OracleClientRepository instance to the business logic and you have made the switch without modifying any business logic code.
Discuss this wiki article and the principle on the corresponding talk page.