AlgoViz

Dependency inversion (DIP)

medium 40 min

The rules of your program should not name the tools they run on.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

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

checkoutCheckoutcreates3 toolsedits0payStripeClientnetworkneededdbPostgresOrdersmethodinsertrows0logFileLoggerdiskneeded

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

switchSwitchedits0lightnothing yet

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

    critical

    The rule speaks SQL, so nothing is hidden.

    Wrong
    class Database(Protocol):    def execute(self, sql): ...
    Right
    class OrderStore(Protocol):    def save(self, order, receipt): ...
  • The default creates the tool

    major

    The import stays in the rule's file, and tests may use the real thing by accident.

    Wrong
    def __init__(self, db=None):    self._db = db or Postgres()
    Right
    def __init__(self, store: OrderStore):    self._store = store
  • A locator inside the rule

    major

    The need is hidden and fails only when the line runs.

    Wrong
    def place(self, order):    Locator.get(OrderStore).save(order)
    Right
    def __init__(self, store):    self._store = store
  • Vendor errors escape

    critical

    The rule must import the vendor to catch them.

    Wrong
    def charge(self, oid, cents):    return sdk.create(cents)
    Right
    try: 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