Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    Composition over Inheritance: A Practical Design Checklist

    Separate changing behavior into explicit collaborators.

    When to compose objects and when to inherit, five checks to decide, and why the order of wrappers is a design decision.

    At a glance

    • Composition: an object holds a collaborator and delegates to it ("has a", "uses a"). Inheritance: a subtype keeps every promise of its base type ("is a").
    • "Prefer composition" is a preference, not a ban. Inheritance fits a stable extension point or a real shared contract.
    • Composition lets independent choices vary on their own: delivery channel, retry rule, audit.
    • Wrappers add indirection, and their order changes behavior. Name the order and test it.
    • A subtype that cannot do what its base promises (a read-only document whose Save always throws) is a sign the hierarchy is wrong.

    Composition or inheritance?

    CompositionInheritance
    Relationshiphas a / uses ais a
    What is reuseda collaborator's behavior, by delegatingthe base class's code and contract
    Varying two thingscombine two collaboratorsone subclass per combination, when subclasses alone encode the choices
    Couplingto the collaborator's type, often an interfaceto the base class's implementation
    Typical fitservices, policies, channels, retriesa stable framework extension point; a true subtype
    Main riskwiring, many small objects, wrapper ordera fragile base class, overrides that break the contract

    A class hierarchy such as EmailNotifier, RetryingEmailNotifier and AuditedSmsNotifier mixes three independent decisions, and every new combination asks for another subclass. With composition, a notification service is given a sender, and retry and audit are separate wrappers chosen when the service is built.

    Wrappers compose, and their order matters

    C#Runs
    Console.WriteLine("audit outside retry:");
    new Audited(new Retrying(new FlakySms(), 3)).Send("order 42");
    Console.WriteLine("retry outside audit:");
    new Retrying(new Audited(new FlakySms()), 3).Send("order 42");
    
    interface INotifier { void Send(string message); }
    
    sealed class FlakySms : INotifier // times out once, then works
    {
        int calls;
        public void Send(string message)
        {
            if (++calls == 1) throw new TimeoutException();
            Console.WriteLine($"  sent: {message}");
        }
    }
    
    sealed class Retrying(INotifier inner, int attempts) : INotifier
    {
        public void Send(string message)
        {
            for (int i = 1; ; i++)
            {
                try { inner.Send(message); return; }
                catch (TimeoutException) when (i < attempts) { Console.WriteLine($"  attempt {i} timed out"); }
            }
        }
    }
    
    sealed class Audited(INotifier inner) : INotifier
    {
        public void Send(string message) { Console.WriteLine("  audit record"); inner.Send(message); }
    }
    Output
    audit outside retry:
      audit record
      attempt 1 timed out
      sent: order 42
    retry outside audit:
      audit record
      attempt 1 timed out
      audit record
      sent: order 42
    • The same three objects, wrapped in a different order, write one audit record or one per attempt.
    • Neither order is wrong: decide whether an audit record means "a send was requested" or "a send was attempted", and test that order.
    • Keep business rules out of generic wrappers: a retry wrapper should not decide whether the customer agreed to SMS.

    Five checks before you choose

    1. What varies? If the channel and the retry rule change separately, represent them separately.
    2. What is promised? A subtype must keep the base contract, including its errors and the side effects callers rely on.
    3. Who owns the lifetime? Decide who creates and disposes each collaborator. Sharing a stateful object by accident causes bugs.
    4. How will it be tested? A small INotifier lets a test simulate success, a timeout and a rejection without sending anything.
    5. Is the abstraction earned? Two similar lines do not justify a hierarchy or an interface. A plain function is fine when nothing varies.

    When inheritance is the right tool

    • A framework gives you a base class to extend, such as DelegatingHandler in an HttpClient pipeline or BackgroundService for a hosted service.
    • The subtype really can be used wherever the base type is expected, with every promise kept.
    • The hierarchy is stable and shallow. Seal classes that are not designed to be extended (sealed).

    The risk is inheriting only to reuse a method, then overriding unrelated behavior to make the subclass fit.

    The read-only subtype

    A base Document promises that Save works for every valid document. A ReadOnlyDocument subclass always throws NotSupportedException. Callers holding a Document cannot rely on the promise, so the subtype breaks substitutability. If the contract had said "check CanSave first", the same exception would be within the contract. Better: a readable document type, and a separate capability for documents that can be saved.

    Common mistakes

    • One subclass per combination of features: compose the independent choices instead.
    • Inheriting to reuse a method: delegate to a collaborator that has it.
    • An interface for every class: add a boundary only where variation, ownership or testing needs one.
    • Wrappers in an unnamed order: state the order and test it.
    • A subtype that refuses its base's operations: split the contract into capabilities.

    In an interview

    What does "favor composition over inheritance" mean? Build behavior by combining objects that delegate to each other, rather than by extending a base class. It keeps independent choices separate and avoids tying code to a base class's implementation.

    When would you still use inheritance? When a framework offers a base class to extend, or when the subtype really keeps every promise of its base type in a stable, shallow hierarchy.

    How does composition help testing? A class that receives its collaborators through its constructor, typed as an interface or an extensible base class, can be given test doubles, so a test can simulate failures without real email or SMS.

    What does composition cost? More objects and wiring, and behavior spread over wrappers whose order matters. Debugging a long chain is harder than reading one class.

    Does composition mean an interface for every class? No. Add an interface where something really varies or must be replaced in tests. Concrete classes and small functions are often enough.

    Check yourself

    An order service must send by email or SMS, with or without retries, with or without audit. What keeps the combinations manageable?

    A One subclass for each combination
    B A sender with retry and audit wrappers
    C One base class with virtual hooks for all three
    D One static method that branches on three flags
    Show answer

    Correct answer: B

    Each independent choice is its own object, and the service is built with the combination it needs.

    Option A: The number of subclasses grows with every new option.

    Option C: Every subclass is tied to one base class that knows all three concerns.

    Option D: One method then implements every combination and keeps growing.

    A base type promises that Save works for every valid document. A subclass always throws NotSupportedException. What is the problem?

    A The subclass breaks the base type's contract
    B The exception should be InvalidOperationException
    C The subclass should be sealed
    D Save should be made virtual
    Show answer

    Correct answer: A

    Code that holds the base type relies on Save working, and this subtype cannot keep that promise.

    Option B: A different exception still breaks the promise.

    Option C: Sealing stops further subclasses; it does not fix this one.

    Option D: Making a method overridable does not change what callers were promised.

    Audit wraps retry, and the first of two send attempts times out. How many audit records are written?

    A None, because the first attempt failed
    B Two, one for each attempt
    C One, for the whole send
    D Three, one more for the timeout
    Show answer

    Correct answer: C

    The audit wrapper runs once and calls the retry wrapper, which makes both attempts inside it.

    Option A: The audit record is written before the attempts start.

    Option B: That happens when retry wraps audit instead.

    Option D: The timeout is handled inside the retry wrapper; audit runs once.

    Sources

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·