Back

Open/Closed

The O in SOLID: code should be open for extension but closed for modification. Add new behavior by adding new code, not by editing working code and stacking more if/else statements.

// Bad: every new shape means editing this function
function area(shape) {
  if (shape.type === "circle") return Math.PI * shape.r ** 2
  if (shape.type === "square") return shape.side ** 2
}

// Good: add new shapes without touching existing code
interface Shape { area(): number }

class Circle implements Shape {
  constructor(private r: number) {}
  area() { return Math.PI * this.r ** 2 }
}
class Square implements Shape {
  constructor(private side: number) {}
  area() { return this.side ** 2 }
}

const total = shapes.reduce((sum, s) => sum + s.area(), 0)

Roadmap