LLD Hub
Learn

Open / Closed PrincipleOpen for extension, closed for modification

Add new behaviour with new classes, not by editing old ones. · Abstractions + polymorphism unlock extension.

Watch

Watch, then scroll down for code and practice.

In code

Discount strategiesTypeScript
interface Discount {
  apply(price: number): number;
}

class NoDiscount implements Discount {
  apply(p: number) {
    return p;
  }
}

class PercentOff implements Discount {
  constructor(private pct: number) {}
  apply(p: number) {
    return p * (1 - this.pct);
  }
}

class Cart {
  total(base: number, d: Discount) {
    return d.apply(base);
  }
}

📘 Key ideas

The principle

You should be able to add new behaviour without modifying existing code. The way to achieve this is to depend on abstractions, not concretions.

The smell

You add a new payment type and have to open PriceCalculator to add another else if. Every new feature requires modifying existing classes.

The fix: Strategy pattern

PriceCalculator accepts a list of DiscountStrategy. New discounts are new classes — PriceCalculator is never touched again.

OCP + OOP

Polymorphism is the mechanism that makes OCP possible. Add new behaviour by adding new subclasses/implementations, not by editing existing ones.

🧠 Practice — Apply What You Learned

🚀 Now apply what you learned

Pick a problem above, write your solution, and get AI feedback on your design.

Start Practice →