SOLID & Design Patterns Interview Question #137

When should inheritance be replaced with composition?

Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced

Quick Interview Answer

Prefer composition when behavior needs to vary independently, be combined dynamically, or avoid a fragile inheritance hierarchy. Inheritance is appropriate when there is a genuine substitutable is-a relationship and the base contract is stable.

Detailed Explanation

Prefer composition when behavior needs to vary independently, be combined dynamically, or avoid a fragile inheritance hierarchy. Inheritance is appropriate when there is a genuine substitutable is-a relationship and the base contract is stable.

Deep inheritance trees often create hidden coupling because subclasses depend on base-class implementation details. Strategy and Decorator are common composition-based alternatives.

Code Example

public class ReportService
{
    private readonly IFormatter _formatter;

    public ReportService(IFormatter formatter)
        => _formatter = formatter;
}

// Behavior can vary without subclassing
// ReportService.