AlgoViz

Object composition

medium 50 min

Build 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

0:00 / 4:23

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

  1. 1986

    Henry Lieberman describes delegation between objects as a way to share behaviour without classes.

  2. 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.

  3. 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.

  4. 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.

Step 1 of 4

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.

Sam and the cleaner

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

Python
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 27
Two independent choices already in the class names. Count what a third choice would do.
Edit and run it in your browser

Product or sum

3×3×3⏟one class per combination=271+3+3+3⏟robot and parts=10\underbrace{3 \times 3 \times 3}_{\text{one class per combination}} = 27 \qquad \underbrace{1 + 3 + 3 + 3}_{\text{robot and parts}} = 10
Three moves, three sensors, three radios. Plus three small interfaces in languages that have them. One more movement: 9 new classes against 1.

The bad shape: one leaf for each combination

«abstract»Robot+ patrol()«abstract»WalkingRobot«abstract»FlyingRobot

1/3Split by movement

The tree must choose one criterion for its first level.

extends (is a)

A tree has one way to divide. Real things divide in several ways at once.

The good shape: one whole, three sockets

Robot+ patrol()+ useLink(link)«interface»Movement+ move()«interface»Sensor+ scan()«interface»Link+ send(data)

1/4Three promises

The robot asks three questions: move, scan, send. It does not know who answers.

has (lives on)implements

Hollow diamonds, because the parts are handed in and may outlive the robot.

How it works

The whole coordinates, the parts work

One patrol

The order of steps belongs to the robot. How a step is done belongs to the part.

Five ways to put objects together

FormThe wholeExampleHome
One part per jobAsks each part its questionRobot with movement, sensor, linkThis page
One exchangeable algorithmPasses one call onRoute planner with a strategyStrategy
A wrapper of the same shapeAdds something before or afterA link that countsDecorator
A list of the same shapeAsks all, or until one answersFirst link that worksChain of responsibility
A treeChildren may be wholes themselvesFolders and filesComposite
Patterns give names to common shapes of composition. The mechanism is always the same: hold and pass on.

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.

Python
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 Noor
The part formats a name. In forwarding it uses its own title. In strict delegation it asks the whole.
Edit and run it in your browser

Time

When is a part chosen?

MomentHowGood forWatch
Compile timeTemplate or generic parameterHot loops, no extra callOne machine code copy per choice
ConstructionConstructor parameterThe normal caseToo many parameters: group them
Between two usesA setter such as useLinkFailover, settings, plansNever in the middle of a use
Every callParameter of the methodThe caller knows bestThe whole keeps nothing

A part fails and is replaced

The robot object is the same in all states. Only one field changes.

A classic

Birds that cannot fly

Python
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 rocket
A penguin gets a part that says no. No method is inherited and then switched off. The full example in four languages is in the Code tab.
Edit and run it in your browser

Why 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)
ExampleA dog is an animalA car has an engine
TieChild depends on how the parent worksWhole depends on a promise
ChosenWhen the code is writtenAt construction or later
You getEverything, wanted or notWhat you pick
TestParent always comes alongParts can be replaced
When each one is right is the subject of Inheritance vs composition. The question is a and has a is in IS-A and HAS-A.

Judgement

To cut or not to cut

Should this become a part?

The fourth question is often forgotten. Two choices that always change together are one part.

Robots may move, scan and send. How do you build them?

BreaksA class per combination
How
WalkingCameraWifiRobot and 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" inside patrol.
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