What is Open-Closed Principle (OCP)?
javascript
// Bad: Modifying existing code for new shapes
class AreaCalculator {
calculate(shape) {
if (shape.type === "circle") {
return Math.PI * shape.radius ** 2;
} else if (shape.type === "square") {
return shape.side ** 2;
}
// Adding triangle? Must modify this function!
}
}
// Good: Open for extension
class Shape {
area() {
throw new Error("Must implement");
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side ** 2;
}
}
// Can add Triangle without modifying existing code!
class Triangle extends Shape {
constructor(base, height) {
super();
this.base = base;
this.height = height;
}
area() {
return (this.base * this.height) / 2;
}
}Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.