QA
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.

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

What are key Clean Code principles for variable naming, function size, and side-effects?