Reducing coupling
medium 40 minTwo parts are coupled when a change in one can force a change in the other.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
Two cords join three kites.
Step 1: Tied
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Create it inside
criticalThe rule now knows the vendor, its address and its lifetime.
Wrongdef __init__(self): self.db = MySQLDatabase("prod-1")Rightdef __init__(self, store): self._store = storeContainer as a locator
majorThe need is hidden, a typo fails at run time, and everything depends on the container.
Wrongdef place(self, o): container.resolve("database").save(o)Rightdef __init__(self, store): self._store = store# main: OrderService(container.resolve(...))Static event bus
majorA class variable is shared by all buses and all tests.
Wrongclass EventBus: _listeners = {}Rightclass EventBus: def __init__(self): self._listeners = {}Event where an answer is needed
criticalTwo customers buy the last item before stock reacts.
Wrongbus.publish(OrderPlaced(o)) # stock will seeRightif not stock.reserve(o.items): return Refused()bus.publish(OrderPlaced(o))Publish before commit
criticalA rollback leaves a mail about an order that does not exist.
Wrongbus.publish(event)db.commit()Rightdb.insert_outbox(event)db.commit()Interface in the vendor's words
minorexecute(sql)couples the service to SQL, whatever the keyword says.Wrongclass Database(Protocol): def execute(self, sql): ...Rightclass 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