"Software entities should be open for extension, but closed for modification."
By not modifying existing, tested code, you eliminate the risk of breaking features that already work.
New features are added as new plugins or modules, keeping the core system clean and manageable.
Developers can work on extensions independently without conflicting changes in the same core file.
The "Power Drill" Analogy
You don't buy a new drill to drive a different screw. You just change the bit. The drill is closed, the bits are open.
Simulate adding features to an application. Toggle between the "Wrong Way" and the "OCP Way" to see how the code evolves.
// --- Core (Locked) ---
class AreaCalculator {
calculate(shapes) {
// Closed for modification!
return shapes.reduce((sum, s) =>
sum + s.area(), 0);
}
}
// --- Extensions (Open) ---
OCP Violation Detected
You modified the core Calculator class to add a new shape. This increases regression risk.
OCP Adherence Verified
Core Calculator class remains untouched (Closed). New logic added via extension (Open).
class AreaCalculator {
calculate(shapes) {
let area = 0;
for (const shape of shapes) {
// Modification required for EVERY new shape!
if (shape.type === 'Rectangle') {
area += shape.width * shape.height;
}
else if (shape.type === 'Circle') {
area += Math.PI * shape.radius ** 2;
}
}
return area;
}
}
Every time you invent a new shape, you must open this file and risk breaking the calculation for other shapes.
// --- Core File (Locked) ---
class AreaCalculator {
calculate(shapes) {
// Does not know about specific shapes!
return shapes.reduce((sum, shape) =>
sum + shape.area(), 0);
}
}
// --- Extension File (New) ---
class Circle {
area() {
return Math.PI * this.radius ** 2;
}
}
The calculator relies on a contract (`.area()`). Adding a Triangle just means creating a `Triangle` class. The calculator sleeps soundly.
Chrome is closed for modification (you can't change its source code), but open for extension (you can write plugins).
Games like Skyrim allow modders to add quests and items without needing the game's original C++ source code.
E-commerce sites use a `PaymentStrategy`. Adding PayPal or Stripe doesn't break the checkout flow logic.
Android/iOS handles core tasks (Closed). Apps extend functionality (Open) via defined APIs.
Remember: Strategic closure is key. You can't be closed against every possible change. Choose your abstractions based on what is most likely to change in the future.
Scenario: You need to add "Dark Mode" to your website.