Open / Closed Principle — Open 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
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
SRP: Fix the Overloaded Logger
You are given a Logger class that does too much: it formats log messages, filters by level…
OCP: Extend Discounts Without Modifying
A PriceCalculator class uses a long if-else chain to apply discounts: if user is Student, …
LSP: The Square–Rectangle Problem
The classic LSP violation: Square extends Rectangle. Since a square's width and height mus…
ISP: Break the Fat Worker Interface
A Worker interface has four methods: work(), eat(), sleep(), requestLeave(). HumanWorker i…
DIP: Decouple the Database Layer
UserService directly instantiates MySQLDatabase inside its constructor: `this.db = new MyS…
Logger / Logging Framework
Design a flexible logging framework that supports multiple log levels, formatters, and out…
Payment Gateway
Design a payment processing system that handles transactions across multiple payment metho…
🚀 Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice →