The Plain Picture#
A power strip. To add a new device, you plug it in. You don't open the strip and solder new wires. The strip is closed for rewiring but open to new plugs.
The Real Name#
Open/Closed Principle (OCP): software should be open for extension but closed for modification. You add behaviour by adding new code (a new class that implements an interface), not by editing working, tested code.
Under the Hood#
The violation — every new plan or promotion edits this method:
int monthlyCredits(String plan) {
int credits = 100;
if (plan.equals("student")) credits += 50;
else if (plan.equals("pro")) credits += 200;
// exam-week promotion? teacher plan? → edit here again, and again...
return credits;
}The fix — each rule is its own class behind one interface; the calculation loops over whichever rules apply:
interface CreditRule {
int adjust(int credits, String plan);
}
class StudentPlanRule implements CreditRule {
public int adjust(int c, String plan) {
return plan.equals("student") ? c + 50 : c;
}
}
class ExamWeekRule implements CreditRule {
public int adjust(int c, String plan) {
return c * 2;
}
}
static int monthlyCredits(String plan, List<CreditRule> rules) {
int c = 100;
for (CreditRule r : rules) c = r.adjust(c, plan); // polymorphism (03_java_oop.md Ch 4)
return c;
}System.out.println(
monthlyCredits("student", List.of(new StudentPlanRule())) +
" " +
monthlyCredits("student", List.of(new StudentPlanRule(), new ExamWeekRule()))
);
// 150 300The exam-week promotion was added without touching monthlyCredits or StudentPlanRule. Turning it off after exams means not passing it
in. This is the Strategy design pattern (Behavioural Patterns (coming soon)) — and it's exactly how
the question-grading loop in Object-Oriented Programming Ch 4 worked.
Signs you need OCP: a growing if/else or switch on a type or a string that appears in several places.
Gotchas
You can't close against every possible change. Apply OCP where change has already happened or clearly will (new plans, new question types, new payment providers). Don't build plugin systems for things that never change (YAGNI, Ch 7).
Check yourself
3 questionsState OCP.
Show answerHide answer
Open for extension, closed for modification — add behaviour with new code, not by editing working code.
Why is a growing if (plan.equals(...)) chain a problem?
Show answerHide answer
Every new case means editing (and risking) working code, often in several places.
Which language feature makes OCP possible?
Show answerHide answer
Polymorphism through interfaces (or abstract classes).