Composition over inheritance
Last updated
Inheritance says one class is a kind of another. Composition says one object has another. Both reuse code, and choosing wrongly makes a program hard to change. In this lesson you'll tell the two apart, watch a family of member classes multiply out of control, replace it with members that hold a borrowing policy, pass work on to the object you hold, and learn when inheritance is still the right tool.
By the end of this lesson you can
- Tell an "is a" relationship from a "has a" one, and pick inheritance or composition to match
- Explain why a class hierarchy built from combinations grows out of control
- Give an object a part it holds, and delegate work to it
- Say when inheritance is still the better choice
"Is a" or "has a"
There are two ways to build a class out of another.
- Inheritance: a DVD is a library item.
class DVD(LibraryItem)means every DVD is also aLibraryItem, with everything a library item has. - Composition: a loan has an item. The loan holds the item in an attribute, as in lesson 3.3. A loan isn't a kind of item.
Line 18 is True: a DVD counts as a library item. Line 19 is False: a loan only holds one. Saying the sentence out loud is a good test. "A DVD is a library item" sounds right. "A loan is a library item" doesn't.
| Sentence | Design | |
|---|---|---|
| A DVD and a library item | A DVD is a library item | Inheritance: class DVD(LibraryItem) |
| A loan and an item | A loan has an item | Composition: self.item = item |
| A member and their loans | A member has loans | Composition: self.loans = [] |
| A member and a borrowing policy | A member has a policy | Composition: self.policy = policy |
The last row is the subject of this lesson.
When a hierarchy goes wrong
The library has three kinds of member. Students can borrow 6 items, staff pay no fines, and everyone else gets the standard deal. Inheritance looks like a fit: a student member is a member.
One small new piece: "pays fines" if self.fines else "no fines" on line 9 picks one of two values. It's an if and else squeezed into one line, for when each side is a single value.
- +limit: int
- +fines: bool
- +name: str
- +__init__(name: str)
- +describe(): str
- +limit: int
- +fines: bool
- Class Member; attributes: limit, fines, name; methods: __init__, describe.
- Class StudentMember; inherits from Member; attributes: limit; no methods of its own.
- Class StaffMember; inherits from Member; attributes: fines; no methods of its own.
- Class StudentStaffMember; inherits from StudentMember and StaffMember; no attributes of its own; no methods of its own.
It works. Then Kim turns up, who is both a student and on the staff. That needs a fourth class, StudentStaffMember, with two parents (lesson 4.7). Now imagine the library adds guest members, who can borrow only 1 item. To cover every mix you'd need GuestMember, GuestStudentMember, GuestStaffMember, GuestStudentStaffMember… Each new kind of member doubles the number of classes.
Try it: add a GuestMember with limit = 1, then the classes for a guest who is also a student or on the staff. Count how many classes you need, and notice they hold almost no code. The classes multiply, but the rules don't.
There's a second problem. If Ana leaves her course and joins the staff, her object is a StudentMember for life. An object can't change its class.
A member has a borrowing policy
The rules, a limit and whether fines apply, aren't what a member is. They're something a member has: a borrowing policy. So make Policy its own small class, here a dataclass from lesson 3.6, and give each member one.
- There's one
Memberclass, and three ready-made policies on lines 11 to 13. - Kim's mix of student and staff rules on line 26 is just another
Policy. No new class is needed. - Ana changes policy on line 30 by changing one attribute, while the program runs.
A guest is now one more line, GUEST = Policy("guest", 1, True), not four more classes.
Delegating to an object you hold
When other code asks a member for a fine, the member doesn't work it out. It passes the job to its policy: self.policy.fine_for(days_late) on line 23. Passing work on to an object you hold is called delegation.
The policy here is a plain class with a method, so different policies can have different fine rules: 25 cents a day up to 500, as in lesson 1.P, or nothing for staff.
- +name: str
- +policy: Policy
- +loans: list[str]
- +__init__(name: str, policy: Policy)
- +can_borrow(): bool
- +fine_for(days_late: int): int
- +limit: int
- +fine_per_day: int
- +max_fine: int
- +__init__(limit: int, fine_per_day: int, max_fine: int)
- +fine_for(days_late: int): int
- Class Policy; attributes: limit, fine_per_day, max_fine; methods: __init__, fine_for.
- Class Member; attributes: name, policy, loans; methods: __init__, can_borrow, fine_for.
- Member holds one Policy in policy.
Code that uses a Member calls sam.fine_for(4) and never needs to know a policy exists. That keeps the design free to change later, which is encapsulation again (lesson 4.2). Line 31 fills Sam's loans from outside only to keep the example short.
When inheritance is still right
None of this makes inheritance bad. It's the right tool when the "is a" sentence is true, stays true, and the child can stand in for the parent anywhere. Python's own exceptions are a family like that, as lesson 4.8 showed.
| If… | Use |
|---|---|
| The child really is a kind of the parent, everywhere and always | Inheritance |
| The child works wherever the parent does (lesson 4.9) | Inheritance |
| The tree stays shallow, one or two levels | Inheritance |
A family of errors, like LibraryError (lesson 4.8) | Inheritance |
| The object has the thing, or uses it | Composition |
| Kinds combine, like student and staff | Composition |
| The part may change while the program runs | Composition |
| You want only some of another class’s methods | Composition |
A good habit: reach for composition first, and use inheritance when the "is a" test clearly passes. The capstone does both: books, DVDs and magazines inherit from LibraryItem, and members hold a policy.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| Reusing code by “is a” | Inheritance, even from several parents | extends, one parent | No inheritance |
| Reusing code by “has a” | An attribute holding the part | A field holding the part | A field holding the part |
| Passing work on | Call the part’s method yourself | The same | The same |
| Advice | “Composition over inheritance” is common advice | The same advice is classic in Java | The language makes the choice for you |
Rust has no inheritance at all, so composition and traits do all the work: see Simple Rust 4.1.
Check what you learned
Three questions. Pick an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Inheritance
- The Python Tutorial: Multiple Inheritance
- The Python Language Reference: Conditional expressions: x if test else y
- The Python Standard Library: dataclasses
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides: Design Patterns (1994): “favor object composition over class inheritance”
- The Java Tutorials: Inheritance: reusing code by extends in Java
- The Rust Programming Language: Inheritance as a Type System and as Code Sharing: Rust reuses code without inheritance