Dependency inversion (DIP)
medium 40 minThe rules of your program should not name the tools they run on.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: who creates whom, who knows whom, and what a swap touches.
Operations
Hard-wired
The rule makes its own tools. Then one tool changes.
Step 1 of 5
Three tools are born
Nobody can hand in another one. The rule chooses.
Step 1: Three tools are born
class Checkout: def __init__(self): self.pay = StripeClient() self.db = PostgresOrders() self.log = FileLogger() def place(self, order): self.pay.create_charge(order.cents) self.db.insert(order) self.log.write("placed")- Good for
- Throwaway scripts
- Costs
- Every swap edits the rule
- Tools named in the rule
- 3
Read the constructor: each creation is an import you cannot escape.
In the real world
The same dependency inversion (dip) doing real jobs. Pick one and step through it.
The switch owns a small port called Light: on and off.
Step 1 of 5
Not wired
A switch soldered to one bulb means a new switch for each new bulb. This switch only needs something with on and off.
Step 1: Not wired
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The port mirrors the tool
criticalThe rule speaks SQL, so nothing is hidden.
Wrongclass Database(Protocol): def execute(self, sql): ...Rightclass OrderStore(Protocol): def save(self, order, receipt): ...The default creates the tool
majorThe import stays in the rule's file, and tests may use the real thing by accident.
Wrongdef __init__(self, db=None): self._db = db or Postgres()Rightdef __init__(self, store: OrderStore): self._store = storeA locator inside the rule
majorThe need is hidden and fails only when the line runs.
Wrongdef place(self, order): Locator.get(OrderStore).save(order)Rightdef __init__(self, store): self._store = storeVendor errors escape
criticalThe rule must import the vendor to catch them.
Wrongdef charge(self, oid, cents): return sdk.create(cents)Righttry: return sdk.create(cents)except SdkError as e: raise PaymentFailed(oid) from e
Interview tips
Draw packages
- Port beside the policy
- Adapter beside the driver
- Main sees both
Show the test
- Build with fakes
- Make failure happen
- Same contract for the real one
Say the limits
- Data still moves
- SQL still differs
- Ports can change
Stop in time
- Values need no port
- No second behaviour: no port
- A function may be enough