Object composition
medium 50 minBuild a big object from small ones.
Chapter mnemonic
Three object relationships
A car is a vehicle, owns its engine, and uses a charger.
A car borrows a public charger for five minutes. Which relationship fits?
Dependency. The car uses the charger for an operation and does not own its lifecycle.
Video lesson · Chapter 1 of 6
Make a prediction
Object composition
1:01Reel
Theory
Read or listen first. About 2 min.
What it is
Object composition means that an object gets its behaviour from other objects that it holds. A robot does not know how to fly. It has a movement part, and that part knows.
The whole delegates: it receives a request and passes it, or a piece of it, to a part. From outside you see one object. Inside, several small ones work together.
The word has two uses. In this page it means building behaviour from parts in general. In a class diagram, composition is the stricter line where the part dies with the whole: that is Aggregation vs composition.
Why it exists
Things that vary independently multiply when they share one class tree. Three ways to move, three sensors and three radios give 27 robots. As parts they give 3 + 3 + 3.
Parts can be chosen late. A class is fixed when the code is written. A part is picked when the object is created, or exchanged while the program runs.
Small parts are easy to test, to read and to use again. And the whole can be tested with parts made of cardboard.
A short history
1986
Henry Lieberman describes delegation between objects as a way to share behaviour without classes.
1994
The book Design Patterns by Gamma, Helm, Johnson and Vlissides gives the advice to favor object composition over class inheritance. Many of its patterns, such as Strategy, Decorator, Bridge and State, are ways to compose.
1998
Mikhajlov and Sekerinski publish a study of the fragile base class problem at ECOOP: one more reason to reuse through a promise and not through a parent.
2012
Go 1 is released. The language has no subclasses. It borrows behaviour by embedding one type in another.
Words to know
- Part, component
- An object that does one job for a bigger one.
- Whole
- The object that holds parts and is seen from outside.
- Has a
- The relation between whole and part. A car has an engine.
- Forwarding
- The whole calls the part, and the part knows nothing about the whole.
- Delegation
- In the strict sense, a part that works on behalf of the whole: calls to self come back to the whole. In daily speech people use it for forwarding too.
- Injection
- Parts are handed in from outside, usually through the constructor.
- Class explosion
- One class for each combination of independent choices.
- Null part
- A part that does nothing, politely. It saves the whole from asking whether a part exists.
- Composition root
- The one place where parts are created and put together.
- Self problem
- A wrapped object calls itself and not its wrapper, so the wrapper is skipped.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Find what varies. Which choices are independent of each other?
Understand it
Start here
One body, many heads
Sam must clean a carpet, a sofa and the yard. The first shop sells complete cleaners. The second sells one body and loose parts.
Frame 1 is the class explosion, 2 to 5 are composition, 6 is testing and 7 is the contract between whole and part.
The smell
Choices that multiply
class WalkingCameraRobot: def patrol(self): return "walks, " + "takes a photo"class WalkingRadarRobot: def patrol(self): return "walks, " + "measures distance" # walks: copiedclass FlyingCameraRobot: def patrol(self): return "flies, " + "takes a photo" # photo: copiedclass FlyingRadarRobot: def patrol(self): return "flies, " + "measures distance"def classes(*choices): n = 1 for c in choices: n *= c return nprint(classes(2, 2), classes(3, 3), classes(3, 3, 3)) # 4 9 27Product or sum
The bad shape: one leaf for each combination
1/3Split by movement
The tree must choose one criterion for its first level.
extends (is a)
The good shape: one whole, three sockets
1/4Three promises
The robot asks three questions: move, scan, send. It does not know who answers.
has (lives on)implements
How it works
The whole coordinates, the parts work
One patrol
Five ways to put objects together
| Form | The whole | Example | Home |
|---|---|---|---|
| One part per job | Asks each part its question | Robot with movement, sensor, link | This page |
| One exchangeable algorithm | Passes one call on | Route planner with a strategy | Strategy |
| A wrapper of the same shape | Adds something before or after | A link that counts | Decorator |
| A list of the same shape | Asks all, or until one answers | First link that works | Chain of responsibility |
| A tree | Children may be wholes themselves | Folders and files | Composite |
Words
Forwarding and delegation
Most code that people call delegation is forwarding: the part does not know who holds it. Strict delegation keeps the original receiver, as a parent class does: when the part calls self.x(), the whole answers. Languages such as Self have it built in. In Java, Python, Go and C++ you pass the whole as a parameter if the part needs it.
class Formatter: title = "Mx" def show(self, name): # forwarding: self is the formatter return f"{self.title} {name}" def show_for(self, whole, name): # delegation: the whole is passed along return f"{whole.title} {name}"class Card: title = "Dr" def __init__(self): self.formatter = Formatter() def forwarded(self): return self.formatter.show("Noor") def delegated(self): return self.formatter.show_for(self, "Noor")print(Card().forwarded(), "|", Card().delegated()) # Mx Noor | Dr NoorTime
When is a part chosen?
| Moment | How | Good for | Watch |
|---|---|---|---|
| Compile time | Template or generic parameter | Hot loops, no extra call | One machine code copy per choice |
| Construction | Constructor parameter | The normal case | Too many parameters: group them |
| Between two uses | A setter such as useLink | Failover, settings, plans | Never in the middle of a use |
| Every call | Parameter of the method | The caller knows best | The whole keeps nothing |
A part fails and is replaced
A classic
Birds that cannot fly
class FlapWings: def fly(self): return "flaps its wings"class NoFly: # a null part: a polite answer, not an empty field def fly(self): return "cannot fly"class Rocket: def fly(self): return "flies with a rocket"class Bird: def __init__(self, name, flying): self.name, self._flying = name, flying def use(self, flying): self._flying = flying def fly(self): return f"{self.name} {self._flying.fly()}"penguin = Bird("Penguin", NoFly())print(Bird("Sparrow", FlapWings()).fly(), "/", penguin.fly())penguin.use(Rocket())print(penguin.fly()) # Penguin flies with a rocketWhy bother
What parts give you
What you gain
Flexible
Change behaviour by exchanging a part, also while the program runs.
Loosely coupled
Whole and part know a small promise, not each other's insides.
Easy to test
Cardboard parts for the whole, and each part alone.
No surprise from a parent
A part cannot change which of your methods it calls behind your back.
One job each
A part has one reason to change.
Reusable
The same radio serves robots, drones and weather stations.
Neighbours
Next to the class tree
Has a or is a, in one look
| Is a (class tree) | Has a (parts) | |
|---|---|---|
| Example | A dog is an animal | A car has an engine |
| Tie | Child depends on how the parent works | Whole depends on a promise |
| Chosen | When the code is written | At construction or later |
| You get | Everything, wanted or not | What you pick |
| Test | Parent always comes along | Parts can be replaced |
Judgement
To cut or not to cut
Should this become a part?
Robots may move, scan and send. How do you build them?
BreaksA class per combination
- How
WalkingCameraWifiRobotand 26 more.- Limit
- Each new choice multiplies. Code is copied between leaves. No change at run time.
- Choose when
- Never with independent choices.
WorksFlags and an if in each method
- How
if self.kind == "fly"insidepatrol.- Limit
- Short for two kinds. Then every kind edits the same methods.
- Choose when
- Two kinds, no sign of more.
StrongOne robot with three parts
- How
- Small promises, one class per way, wiring outside.
- Limit
- More names to learn, and rules between parts need a home.
- Choose when
- Two or more independent choices.
Summary
The whole topic in one minute.
Find the choices that vary on their own. Give each a small promise and a family of parts. Let the whole hold one part of each family and only coordinate.
Wire in one place, keep rules between parts in one place, and use a null part instead of an empty field. Swap a part only between two uses of it.
Composition is not free. It adds objects, hops and names. When nothing varies, one plain class is the better design.
- A whole holds parts and passes work on. Order belongs to the whole, the how belongs to the part.
- Independent choices: sum instead of product.
- Most delegation in daily code is forwarding. The part does not know the whole.
- Null part instead of an empty field.
- Wire in one place. Put rules between parts in one place.
- Swap between uses, never in the middle of one.
- If nothing varies, do not cut.
Sources
- Composition over inheritance (with Design Patterns, 1994)
- Delegation, forwarding and Lieberman 1986
- Fragile base class (with ECOOP 1998)
- Go release history (Go 1, March 2012)
- Effective Go: embedding
- Kotlin: delegation
- React: composition vs inheritance
- Unity: introduction to components
- Bevy: ECS
- Java tutorial: buffered streams
- Guava: collection helpers
- Python: logging
- ASP.NET Core: HTTP requests
- Kubernetes: Pods