TechnicalMedium OOP & Design
Why is composition often preferred over inheritance?
Asked for Backend Developer, Mobile Developer
Why they ask this: Checks design maturity; deep inheritance trees are a common source of rigid code.
Answer
- Inheritance ("is a") ties a child class tightly to its parent. A change in the parent can break every child, and deep hierarchies become hard to change.
- Composition ("has a") builds behaviour by holding other objects and delegating to them. Parts can be swapped, tested alone and combined freely.
php
// Inheritance: every new notification channel needs a new subclass
class SmsOrderNotifier extends OrderNotifier { /* ... */ }
// Composition: inject the channel
final class OrderNotifier
{
public function __construct(private NotificationChannel $channel) {}
public function notify(Order $order): void
{
$this->channel->send($order->customer, "Order #{$order->id} confirmed");
}
}Inheritance is still fine for a true, stable "is a" relationship with shared behaviour. Flutter is a good example of composition: UIs are built by nesting small widgets rather than extending big ones.
Can you explain this in your own words?