Circular dependencies
medium 45 minTwo classes or modules that need each other, directly or through others, form a cycle.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who needs whom, who can be created first, and which arrow goes away.
Operations
The container gives up
Two constructors that need each other.
Step 1 of 4
Ask for orders
Orders go on the path: in creation.
Step 1: Ask for orders
def get(self, name): if name in self._ready: return self._ready[name] if name in self._path: raise CycleError(self._path + [name]) self._path.append(name) made = self._makers[name](self) self._path.pop() self._ready[name] = made return made- Good for
- Seeing a construction cycle
- Costs
- Start-up fails
Print the path, not only the last name.
In the real world
The same circular dependencies doing real jobs. Pick one and step through it.
A ring that appears in many interview designs.
Step 1 of 4
Both know each other
The controller moves the elevator, the elevator calls the controller on arrival.
Step 1: Both know each other
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The interface on the wrong side
majorIf the interface lives with the implementer, the import still points there.
Wrong# customers.pyfrom orders import OrderHistoryRight# customers.py owns itclass OrderHistory(Protocol): ...Import inside the function as a habit
majorThe program starts, and the ring is invisible.
Wrongdef f(self): from orders import OrderServiceRight# shared.py holds what both needfrom shared import CustomerHalf built objects escape
criticalSomebody calls before the setter ran.
Wrongorders = OrderService()bus.register(orders)orders.customers = customersRightorders = OrderService(directory)bus.register(orders)Events that answer events
criticalThe ring moved to run time.
Wrongdef on_stock(self, s): self.set_price(s * 10)Rightif new == self.value: returnself.set_price(new)Ownership in both directions
majorWith reference counting neither is freed.
Wrongshared_ptr<Node> parent;Rightweak_ptr<Node> parent;
Interview tips
Name the kind
- Module
- Construction
- Call
Label the arrows
- Which method needs it?
- Is an answer needed?
- For how long?
Cut
- Extract first
- Then port or event
- Merge if it is one thing
Guard
- Check in the build
- List only gets shorter
- Own downwards, look upwards