SOLID & Design Patterns Interview Question #12

Why is composition often preferred over inheritance?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

Composition builds behavior by combining collaborating objects, while inheritance creates an is-a relationship and couples a subtype to a base type's contract and implementation decisions.

Detailed Explanation

Composition builds behavior by combining collaborating objects, while inheritance creates an is-a relationship and couples a subtype to a base type's contract and implementation decisions.

Composition is often more flexible because behavior can be replaced independently and selected at runtime. Inheritance remains appropriate when a genuine substitutable hierarchy exists and the base contract is stable.

Code Example

public class CheckoutService
{
    private readonly IDiscountStrategy _discount;

    public CheckoutService(IDiscountStrategy discount)
    {
        _discount = discount;
    }
}