SOLID Principles
5 nguyên tắc cho OOP scale-friendly. Áp dụng đa số khi codebase > 1000 LOC + nhiều dev.
S · Single Responsibility
1 class/function = 1 lý do thay đổi. Ví dụ: UserService chỉ handle user, không lo email.
// Bad: UserService làm 3 việc
class UserService {
createUser() { /* validate, save, send email */ }
}
// Good: tách
class UserService { create() { /* save */ } }
class EmailService { sendWelcome() {} }
class UserValidator { validate() {} }
O · Open/Closed
Open for extension, closed for modification. Thêm feature bằng strategy/composition thay vì sửa code cũ.
// Bad: thêm payment method = sửa switch
function pay(method) {
if (method === 'visa') {} else if (method === 'paypal') {}
}
// Good: strategy pattern
interface PaymentMethod { pay(amount: number): Promise<void> }
class VisaPayment implements PaymentMethod {}
class PaypalPayment implements PaymentMethod {}
// Thêm Momo? Tạo class mới, không sửa Pay function.
L · Liskov Substitution
Subclass phải dùng được như parent — không break contract.
// Bad: Square extends Rectangle nhưng break setWidth
class Rectangle { setWidth(w) {} setHeight(h) {} }
class Square extends Rectangle {
setWidth(w) { this.w = w; this.h = w; } // ❌ surprising
}
// Good: composition over inheritance
interface Shape { area(): number }
class Square implements Shape {}
class Rectangle implements Shape {}
I · Interface Segregation
Interface nhỏ > interface bloat. Client không phụ thuộc method không dùng.
// Bad: 1 interface ép mọi worker implement đủ
interface Worker { code(); test(); deploy(); manage(); }
// Good: tách
interface Coder { code() }
interface Tester { test() }
interface Deployer { deploy() }
D · Dependency Inversion
Depend on abstraction, not concretion. Inject dependency thay vì new bên trong.
// Bad: hard couple
class OrderService {
constructor() { this.db = new PostgresDB(); } // ❌
}
// Good: inject abstraction
interface Database { save() }
class OrderService {
constructor(private db: Database) {} // ✓
}
// Test: inject MockDB. Prod: PostgresDB. Đổi sang Mongo? Implement Database.