Beginner LevelSoftware Engineering Principles
Why is Composition Over Inheritance a fundamental object-oriented design principle?
❓ Interview Prompt: Explain the Fragile Base Class problem, class inheritance rigidity, dynamic composition using interfaces, and code flexibility.
Composition Over Inheritance states that objects should achieve polymorphic behavior and code reuse by combining small, focused objects (composition) rather than inheriting from a parent class hierarchy (inheritance):
Why Inheritance Fails (Fragile Base Class Problem):
•
Deep class hierarchies create tight coupling: modifying a parent class method can break unexpected child subclasses.
•
Inheritance forces a rigid "is-a" relationship, whereas composition provides a flexible "has-a" relationship that can be changed dynamically at runtime!
Code Implementation Example
typescript
interface Logger { log(msg: string): void; }
class ConsoleLogger implements Logger { log(msg: string) { console.log(msg); } }
// ✅ Composition: OrderService HAS-A Logger (injected interface)
class OrderService {
constructor(private logger: Logger) {} // Flexible composition
placeOrder(id: string) {
this.logger.log('Order \\${id} placed.');
}
}💡Implementing Composition Over Inheritance via dependency injection.
🎯 Interview Key Takeaway
Prefer composition over inheritance to prevent fragile base class coupling and allow dynamic runtime behavior swaps.
#Composition#Inheritance#OOP#Beginner
Back to all Software Engineering Principles Questions→