Object composition
medium 50 minBuild a big object from small ones.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Watch calls travel from the whole to its parts, and parts being exchanged.
Operations
One patrol
The robot knows the order. The parts know how.
Step 1 of 5
A robot and three parts
Each part is an object of its own. The robot holds them.
Step 1: A robot and three parts
def patrol(self): place = self._movement.move() data = self._sensor.scan() return self._link.send(f"{place} {data}")- Good for
- Independent choices
- Costs
- Three small promises
- Classes for 3 x 3 x 3
- 10, not 27
If the method of the whole reads like a story, the cuts are right.
In the real world
The same object composition doing real jobs. Pick one and step through it.
The number of classes as choices arrive.
Step 1 of 5
Two choices of two
| Tree: leaves | Parts: classes | |
|---|---|---|
| 2 x 2 | 4 | 5 |
| 3 x 2 | ||
| 3 x 3 | ||
| 3 x 3 x 3 | ||
| 4 x 3 x 3 |
The tree is smaller: 4 against 5.
Step 1: Two choices of two
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The whole creates its parts
majorTests need the real thing, and another combination needs another class.
Wrongdef __init__(self): self._link = Wifi()Rightdef __init__(self, link): self._link = linkReaching through
majorCallers know the part. Now it cannot be exchanged.
Wrongrobot.link.modem.restart()Rightrobot.recover() # the robot passes it onAn empty field
minorEvery method must ask whether the part exists, and one forgets.
Wrongif self._link is not None: self._link.send(data)Rightself._link.send(data) # NoLink does nothingParts that know each other
criticalEach new part must know all others. Pairs grow with the square.
Wrongclass Radar: def scan(self, movement): if isinstance(movement, Flying): ...Rightbuild(parts) # checks rules between partsAssign and close
criticalWork in progress still holds the old part.
Wrongold, self._link = self._link, newold.close()Rightold.retire() # closed by its last userForward everything around a guard
criticalA method that is added to the inner class later goes around the check.
Wrongdef __getattr__(self, name): return getattr(self._account, name)Rightdef withdraw(self, n): self._check(n) self._account.withdraw(n)
Interview tips
Find the cut
- Which choices are independent?
- Adjectives in class names
- Always together: one part
Keep promises small
- One question
- A named failure
- A fake in three lines
One place for wiring
- Create and combine outside
- Rules in the builder
- A valid whole or all problems
Say the price
- More names
- More hops
- Not closed against new questions