AlgoViz

Circular dependencies

medium 45 min

Two classes or modules that need each other, directly or through others, form a cycle.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:48

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

needscontainerContainerpathordersordersOrderServicestatein creationcustomersCustomerServicestateunknowncreate

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

controllerControllernext jobgo to 5elevatorElevatorfloor3knowscontroller

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

    major

    If the interface lives with the implementer, the import still points there.

    Wrong
    # customers.pyfrom orders import OrderHistory
    Right
    # customers.py owns itclass OrderHistory(Protocol): ...
  • Import inside the function as a habit

    major

    The program starts, and the ring is invisible.

    Wrong
    def f(self):    from orders import OrderService
    Right
    # shared.py holds what both needfrom shared import Customer
  • Half built objects escape

    critical

    Somebody calls before the setter ran.

    Wrong
    orders = OrderService()bus.register(orders)orders.customers = customers
    Right
    orders = OrderService(directory)bus.register(orders)
  • Events that answer events

    critical

    The ring moved to run time.

    Wrong
    def on_stock(self, s): self.set_price(s * 10)
    Right
    if new == self.value: returnself.set_price(new)
  • Ownership in both directions

    major

    With reference counting neither is freed.

    Wrong
    shared_ptr<Node> parent;
    Right
    weak_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