Glossary / Composition
Composition
Composition builds behavior by combining objects that collaborate, rather than deriving a type from a base class. It encourages explicit dependencies, independent variation, and replaceable implementations, making it a strong default for application services and domain components.
Object collaboration
A class can receive collaborators through constructors or methods and delegate focused responsibilities to them. Dependency injection containers may construct graphs, but composition does not require a framework. Interfaces help define boundaries where substitution is valuable; concrete types are fine for stable, local collaborators.
public sealed class Checkout(IPriceCalculator prices, IPaymentGateway payments)
{
public Task ChargeAsync(Order order, CancellationToken token) =>
payments.ChargeAsync(prices.Total(order), token);
}
Composition avoids base-class protected state and override-order coupling, but can create too many tiny abstractions or pass-through wrappers. Dependency graphs still need clear ownership, lifetimes, and disposal. Cycles between services indicate boundary problems and can break container construction.
Engineering guidance
Use composition when responsibilities can change independently, dependencies need test doubles, or multiple implementations are expected. Keep constructors explicit and graphs acyclic. Avoid overusing interfaces solely for mocking; test real collaborators where practical. Use inheritance when there is a genuine substitutable subtype with a stable behavioral contract.
Interview questions
- Composition vs inheritance? Composition delegates to collaborators; inheritance specializes a base type.
- Why favor composition? It reduces coupling to base internals and allows independent variation.
- Does composition require interfaces? No, though interfaces help at meaningful substitution boundaries.
- What risks remain? Excessive indirection, unclear lifetimes, dependency cycles, and ownership ambiguity.
- When is inheritance appropriate? When derived types preserve base behavior and are substitutable.