Open-closed Principle
-o0O0o-
“Software entities (classes, modules, methods, etc.) should be open for extension, but closed for modification”
-o0O0o-
PDF:
Model Format
MagicDraw
The “Open/Closed Principle” (OCP) states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”; that is, such entities should allow their behaviour to be extended without modifying their source code.
The “Open/Closed Principle” (OCP) was first advocated by Bertrand Meyer in the first edition (1988) of his book “Object-Oriented Software Construction” and is considered by many to be the cornerstone of object-oriented design because it underlays many other principles, patterns, and even methodologies.
Open–closed principle is one of the five SOLID principles of object-oriented design compiled by Robert C. Martin.
Code Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class AccountClient { public boolean doSomething(Account a) { switch (a.account_type) { case checkingAcc : foo(a); break; case savingsAcc : bar(a); break; case investmentAcc : qux(a); break; default : hmmm(a); } /* * Problem: it is impossible to add a new account type without modifying the code. */ } |