AlgoViz

Reducing coupling

medium 40 min

Two parts are coupled when a change in one can force a change in the other.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

See it run

Who knows whom, and how far does a change travel?

Operations

The service builds its tools

Two `new` lines, and everything that follows from them.

Step 1 of 4

Two vendors inside

newnewtestunit testneedswaitingserviceOrderServiceknows2 vendorsdbMySQLDatabaseurlprod-1emailSmtpEmailSenderserverup

The service creates both tools. It knows their names, addresses and lifetimes.

Step 1: Two vendors inside

class OrderService:    def __init__(self):        self.db = MySQLDatabase("prod-1")        self.email = SmtpEmailSender()    def process_order(self, order):        self.db.save(order)        self.email.send(order.email, "ok")
Good for
Throwaway scripts
Costs
Vendors everywhere

Ask how you would test the `if` in this class.

In the real world

The same reducing coupling doing real jobs. Pick one and step through it.

A pull and a tear travel along the cords.

Step 1 of 4

Tied

cordcordredLee's kitestateupblueNoor's kitestateupyellowAsha's kitestateup

Two cords join three kites.

Step 1: Tied

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Create it inside

    critical

    The rule now knows the vendor, its address and its lifetime.

    Wrong
    def __init__(self):    self.db = MySQLDatabase("prod-1")
    Right
    def __init__(self, store):    self._store = store
  • Container as a locator

    major

    The need is hidden, a typo fails at run time, and everything depends on the container.

    Wrong
    def place(self, o):    container.resolve("database").save(o)
    Right
    def __init__(self, store): self._store = store# main: OrderService(container.resolve(...))
  • Static event bus

    major

    A class variable is shared by all buses and all tests.

    Wrong
    class EventBus:    _listeners = {}
    Right
    class EventBus:    def __init__(self): self._listeners = {}
  • Event where an answer is needed

    critical

    Two customers buy the last item before stock reacts.

    Wrong
    bus.publish(OrderPlaced(o))   # stock will see
    Right
    if not stock.reserve(o.items): return Refused()bus.publish(OrderPlaced(o))
  • Publish before commit

    critical

    A rollback leaves a mail about an order that does not exist.

    Wrong
    bus.publish(event)db.commit()
    Right
    db.insert_outbox(event)db.commit()
  • Interface in the vendor's words

    minor

    execute(sql) couples the service to SQL, whatever the keyword says.

    Wrong
    class Database(Protocol):    def execute(self, sql): ...
    Right
    class OrderStore(Protocol):    def save(self, order): ...

Interview tips

  • Ask who else changes

    • For names, formats, order, timing
    • Near or far?
    • Often or never?
  • Needs in the constructor

    • An honest list
    • More than five: split the class
    • One root chooses
  • Call or event

    • Decision: call
    • Reaction: event
    • Handlers take duplicates
  • Know when not

    • Stable neighbour: call it
    • Same module: cohesion
    • One listener: no bus