SOLID Principles
SRP, OCP, LSP, ISP, DIP — the five pillars of maintainable OOP.
28 minLevel 17 of 20
S — Single Responsibility
A class should have one reason to change. Split user creation, email, and audit logging.
SRP
class UserService { create(name: string) { return { name }; } }
class Mailer { send(to: string) { console.log("mail", to); } }
class Audit { write(e: string) { console.log("audit", e); } }
const users = new UserService();
const u = users.create("Ada");
new Mailer().send("ada@ex.com");
new Audit().write("created " + u.name);O & L — Open/Closed & Liskov
Open for extension, closed for modification — add classes instead of editing switches. Subtypes must honor parent contracts (no surprising throws).
OCP
interface Discount { rate(): number; }
class VipDiscount implements Discount { rate() { return 0.2; } }
class StudentDiscount implements Discount { rate() { return 0.1; } }
function price(base: number, d: Discount) { return base * (1 - d.rate()); }
console.log(price(100, new VipDiscount()), price(100, new StudentDiscount()));I & D — ISP & DIP
Many small interfaces beat fat ones. Depend on abstractions. Explore each letter in the SOLID Explorer.
DIP
interface Repo { save(x: string): void; }
class MemoryRepo implements Repo { save(x: string) { console.log("save", x); } }
class Service { constructor(private repo: Repo) {} run(x: string) { this.repo.save(x); } }
new Service(new MemoryRepo()).run("ok");Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice