Composition: is-a vs has-a
“What is composition, and when do you use it instead of inheritance?”
Inheritance says a class **is a** kind of another. Composition says a class **has a** part and calls it. Use it when one part changes for a different reason than the rest.
See it
1/9Before. is the parent. and inherit from it: each is a contract.
In plain words
Inheritance is for a true family: a is a kind of , so it gets the contract's data and methods. Composition is for a part: a contract has a late-fee rule, keeps it in a field, and calls it when it needs a fee. You reach for composition when one part changes for a different reason than the rest, like late fees changing per lender (BMW FS, UDC). With inheritance only, every kind × every lender becomes its own class, and the count multiplies. With composition, you write each kind once and each rule once, and you plug the rule in through the .
- Inheritance is an is-a relationship: a lease is a kind of contract. Composition is has-a: a contract has a late-fee rule and calls it, instead of being a special kind of contract for each rule.
- I use composition when one part changes for a different reason than the rest. Late fees differ per lender, so with subclasses I'd need a class for every kind and lender pair, and that multiplies. With composition I write two contract kinds and one class per rule, and they just add up.
- In C# the contract is given its rule when it's built, through its constructor, as an . That's exactly what does, and it means in a unit test I can pass in a fake rule.
- So my rule of thumb is: favour composition over inheritance. I keep inheritance for a real family that shares data and code, and I keep it to two levels.
In the lending API
The rule as an interface, two rules, the contract that holds one, and the code that builds it. Press Next line to walk through.
Lending.sln · where these 6 files sit
- src/
- Domain/
- Fees/
- Fees/
- Billing/
- Domain/
What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
Is this the strategy pattern?
Yes. When the part you hold is a swappable rule behind an interface, that's called the strategy pattern. is a strategy.
Composition vs aggregation?
Both are has-a. Strictly, composition means the whole creates and owns the part; aggregation means the part is passed in and can live on its own, like our rule. Interviewers rarely push this: "composition over inheritance" covers both. Say has-a and give the example.
How do you test it?
Pass a fake rule that always returns, say, 7, and check adds 7. You test the contract without caring about any real client's fee rules.
Traps
- Don't say
Composition means you never use inheritance.SayI still inherit for a true family, like Loan and Lease from Contract. I compose the part that varies on its own. - Don't say
Has-a just means the class has a property.SayIt means it holds another object and hands it work, usually behind an interface so the part can be swapped.