1. Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.
❓ Context: Detail Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles.
// ❌ Violating Dependency Inversion
class OrderProcessorBad {
private mysqlDb = new MySQLDatabase(); // Tight coupling
processOrder(orderId: string) {
this.mysqlDb.saveOrder(orderId);
}
}
// ✅ SOLID: Applying Dependency Inversion & Open/Closed
interface OrderRepository {
saveOrder(orderId: string): void;
}
class PostgresOrderRepository implements OrderRepository {
saveOrder(orderId: string) {
console.log('Saving order \\${orderId} to PostgreSQL');
}
}
class OrderProcessorGood {
constructor(private repo: OrderRepository) {} // Injected abstraction
processOrder(orderId: string) {
this.repo.saveOrder(orderId);
}
}Applying SOLID principles reduces code coupling, improves unit test coverage, and extends code maintainability.