What is composition over inheritance and when do you prefer it?
Short answer
Composition builds behaviour by holding other objects rather than inheriting; it avoids deep, rigid hierarchies and the fragile base-class problem. Prefer it unless there is a true is-a relationship.
Advertisement
AModel answer
Composition builds behaviour by holding other objects rather than inheriting; it avoids deep, rigid hierarchies and the fragile base-class problem. Prefer it unless there is a true is-a relationship.
class Car { private readonly Engine _engine; public Car(Engine e)=>_engine=e; }Real-world example
Injecting an IPaymentGateway into an OrderService instead of subclassing a base service.