InheritanceVSComposition
The Problem
Scenario A β Inheritance seems right:
You have a base Repository<T> class with common CRUD methods. UserRepository extends Repository<User> adds a findByEmail() method. The base handles connection management, error wrapping, and logging. Every repo needs this exact behavior β inheritance shares it cleanly.
Scenario B β Composition wins:
You are building notification senders. An EmailSender sends emails. An SMSSender sends SMS. A PushSender sends push. Now the PM asks: "Some users want email + SMS, some want SMS + push, some want all three." Inheriting from multiple senders is impossible (no multiple inheritance in TS). Composition lets you combine channels freely.
Why They Look Alike
Both achieve code reuse. Both let a class use behavior defined elsewhere. A UserRepository extends BaseRepository and a UserService with an injected repository field both get access to CRUD methods.
From the outside, both UserRepo_Inherit.find() and UserService.find() (delegated) do the same thing. The difference is in how tightly the child is bound to the parent.
The Core Difference
| Aspect | Inheritance | Composition |
|---|---|---|
| Relationship | is-a (compile-time, permanent) | has-a (runtime, swappable) |
| Coupling | Tight β child sees protected members, depends on parent's implementation | Loose β only depends on the interface |
| Flexibility | Fixed at class definition time | Configurable at runtime |
| Multiple reuse | Single inheritance only (TS/Java) | Inject as many collaborators as needed |
| Fragile base class | Yes β parent changes can break children | No β interface contract is the boundary |
| When it breaks | When the "is-a" relationship is false, or the parent evolves | When the delegation overhead isn't worth it for simple hierarchies |
One sentence: Inheritance is "I am a kind of X" (fixed); Composition is "I use an X" (flexible).
Side-by-Side Code
Inheritance β Breaks when requirements change
| 1 | class NotificationSender { |
| 2 | protected format(msg: string): string { |
| 3 | return `[${new Date().toISOString()}] ${msg}`; |
| 4 | } |
| 5 | send(to: string, msg: string): void { |
| 6 | console.log(`Sending to ${to}: ${this.format(msg)}`); |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | class EmailSender extends NotificationSender { |
| 11 | send(to: string, msg: string): void { |
| 12 | console.log(`Email to ${to}: ${this.format(msg)}`); |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | class SMSSender extends NotificationSender { |
| 17 | send(to: string, msg: string): void { |
| 18 | console.log(`SMS to ${to}: ${this.format(msg)}`); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | // Problem: user wants Email + SMS. Can't extend both. |
| 23 | // class EmailAndSMS extends EmailSender, SMSSender {} // TS error |
Composition β Combines freely
| 1 | interface NotificationChannel { |
| 2 | send(to: string, msg: string): Promise<void>; |
| 3 | } |
| 4 | |
| 5 | class EmailChannel implements NotificationChannel { |
| 6 | async send(to: string, msg: string) { |
| 7 | console.log(`Email to ${to}: ${msg}`); |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | class SMSChannel implements NotificationChannel { |
| 12 | async send(to: string, msg: string) { |
| 13 | console.log(`SMS to ${to}: ${msg}`); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | class NotificationService { |
| 18 | constructor(private channels: NotificationChannel[]) {} |
| 19 | |
| 20 | async notify(to: string, msg: string): Promise<void> { |
| 21 | const formatted = `[${new Date().toISOString()}] ${msg}`; |
| 22 | await Promise.all(this.channels.map(ch => ch.send(to, formatted))); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // Mix and match at runtime |
| 27 | const emailAndSms = new NotificationService([new EmailChannel(), new SMSChannel()]); |
| 28 | const allChannels = new NotificationService([new EmailChannel(), new SMSChannel(), new PushChannel()]); |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| True "is-a" with shared implementation (abstract base class) | Inheritance | Base class provides real behavior children need |
| "is-a" but only for the interface contract | Composition (implement interface) | Don't inherit implementation you don't need |
| Need to combine multiple behaviors | Composition | Can't multiply inherit in TS |
| The base class is likely to change | Composition | Avoid fragile base class |
| Deep hierarchy (>2 levels) | Refactor to Composition | Deep trees become rigid and hard to understand |
| Framework requires it (e.g., React class components, TypeORM entities) | Inheritance | Follow the framework's model |
| Testing requires swapping the dependency | Composition | Inject a mock via the interface |
The Trick Question
"Your
BaseControllerhas 5 shared methods: auth check, rate limit, error formatting, request logging, response caching. Every controller extends it. Is this good use of inheritance?"
It looks right, but it's actually composition territory. Those 5 concerns are independent β you might want rate limiting without caching, or logging without auth. Inheriting all of them couples every controller to all 5. In NestJS, these are middleware, guards, interceptors, and pipes β composed via decorators, not inherited. The framework chose composition for exactly this reason.
Interview Angles
Q: When is inheritance still the right call?
When the "is-a" relationship is genuine and stable: TypeORMRepository extends Repository, NestJS Controller extends BaseController (framework-required). Keep it shallow (1-2 levels). If you can't say "X is a Y" without squinting, use composition.
Q: What is the "fragile base class" problem?
Changing a base class method's behavior can silently break all subclasses. Example: BaseRepository.save() starts calling this.validate() internally β subclasses that override validate() get unexpected behavior. With composition, the interface contract is the only coupling point.
Q: How does the "favor composition over inheritance" rule apply in practice? Default to composition. Use inheritance only when: (1) the framework requires it, (2) the hierarchy is shallow and stable, (3) subclasses genuinely share implementation (not just interface). Most backend services should be composed from injected collaborators, not inherited from base classes.
Q: Is TypeScript's implements inheritance or composition?
Neither β it's a contract. implements says "I conform to this interface" without inheriting any code. It's the tool for programming to an interface (DIP). You then compose behavior by injecting dependencies that satisfy those interfaces.