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
Reducing coupling
1:04Reel
Theory
Read or listen first. About 2 min.
What it is
Coupling is how much one part must know about another. If OrderService builds a MySQLDatabase itself, it knows the class, how to create it, and when it lives. A change in any of these is a change in OrderService.
Tight coupling means that many details are shared, so changes travel. Loose coupling means that little is shared and the shared part rarely changes. The partner of coupling is cohesion: things that change together should live together, see Achieving modularity.
Not every arrow is bad. A class that uses String is coupled to String, and nobody minds, because String is stable. What hurts is strong knowledge of something that changes and is far away.
Why it exists
A change in a tightly coupled program spreads: one column is renamed and five files, two teams and a release are involved.
Tests suffer first. If a class creates its own database, every test of it needs a database. Hard to test is often the earliest sign of coupling.
Loose coupling has a price: one more indirection, more names, and harder to follow with the debugger. So it is bought where change or test is expected, not everywhere.
A short history
1974
Stevens, Myers and Constantine publish Structured Design, the article that makes coupling and cohesion standard words. The ladder of coupling kinds comes from this work.
1994
The book Design Patterns by Gamma, Helm, Johnson and Vlissides gives the advice to program to an interface, not an implementation. Mediator, Facade and Observer in it are about coupling.
2004
Martin Fowler's article on containers names Dependency Injection and compares it with the Service Locator. It is dated 23 January 2004.
2017
Fowler's article of 7 February 2017 separates four things that people all call event driven: notification, carrying state, event sourcing and CQRS.
Words to know
- Coupling
- How far a change here can force a change there.
- Cohesion
- How much the things inside one part belong together.
- Dependency injection
- A part receives what it needs from outside instead of creating it.
- Composition root
- The one place, near
main, where concrete classes are chosen and joined. - Port and adapter
- The interface that a part owns, and the class that connects it to a real tool.
- Service locator
- An object you ask for services by name or type. The need is hidden inside the method.
- Temporal coupling
- Two calls must happen in a certain order, and nothing in the code forces it.
- Connascence
- Two pieces are connascent if changing one needs a change in the other to stay correct. Named by Meilir Page-Jones.
- Fan in, fan out
- How many parts use this one, and how many it uses.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Find the tie. What does A know about B?
Understand it
Kites on one string
Lee, Noor and Asha fly kites. Look at the strings, not at the kites.
Even the last picture has a tie: the meaning of the whistle. Loose does not mean nothing.
The ladder of coupling
From worst to best. The kinds come from structured design, and the last row is how we use the words for objects and events.
| Kind | Grade | What is shared | Example | First step down |
|---|---|---|---|---|
| Content | worst | the inside: one part changes another's data | order.service._cache.clear() | private state and a method, see Ensuring proper encapsulation |
| Common | bad | global data that many parts write | CONFIG['db'] = x | pass the value in |
| Control | moderate | a flag that steers the other's logic | save(order, True) | two methods, or a strategy object |
| Stamp | acceptable | a whole structure of which a part is used | sendMail(order) needs only the address | pass the fields, or a small type |
| Data | good | only the values needed | sendMail(to, text) | stay here for plain calls |
| Message | loose | a message or event that both agreed on | publish(OrderPlaced) | use it when many listen or time may pass |
class Mailer: def __init__(self): self._queue = [] def send(self, to, text): self._queue.append((to, text)) def waiting(self): return len(self._queue)class Order: def __init__(self, email): self.email, self.cents, self.lines = email, 500, []m, o, LANG = Mailer(), Order("lee@example.com"), {"now": "en"}m._queue.append((o.email, "hi")) # content: writes the insidedef common(order): # common: reads a global m.send(order.email, {"en": "Thanks", "de": "Danke"}[LANG["now"]])def control(order, as_gift): # control: a flag picks the path m.send(order.email, "A gift" if as_gift else "Thanks")def stamp(order): # stamp: needs one of three fields m.send(order.email, "Thanks")def data(to, text): # data: exactly what is needed m.send(to, text)common(o); control(o, True); stamp(o); data(o.email, "Thanks")LANG["now"] = "fr" # somebody far awaytry: common(o)except KeyError as e: print("global changed, mail broke:", e)print(m.waiting(), "mails")The bad shape and the good shape
Tight: the service builds its tools
1/2The service
It wants to save and to tell the customer. Those are its two needs.
owns (dies together)
Loose: the service states its needs
1/3Needs, as interfaces
The service owns two small interfaces, in its own words: save an order, send a text.
usesimplements
Loose
- Needs arrive in the constructor
- Values are passed, results returned
- One method per intention
- Callers tell, owners decide
- A change stays in one part
Tight
newinside business code- Globals and static state
- Boolean parameters
- Callers read fields and decide
- Changes come in groups of files
Who creates what, and when
Injection at run time
The place where concrete classes are joined is the composition root. It is tightly coupled to everything, and that is fine: it is one short file, near main, and it has no rules of its own. That the interfaces belong to the service and not to the vendor is the topic of Dependency inversion.
Five techniques
Dependency injection
Pass what is needed. The constructor becomes an honest list of needs.
Program to interfaces
Know what it does, not what it is. Keep the interface in the words of its user.
Events
Announce that something happened. Others react. Good for many listeners or later work.
Facade
One simple front for a complicated subsystem. Callers know one class and not nine. See Facade.
Mediator
Parts talk to a coordinator, not to each other: n parts need n ties, not n x (n - 1) / 2. See Mediator.
Which technique?
OrderService needs a database. How does it get one?
Breaksnew MySQLDatabase() in the service
- How
- Short. Works today.
- Limit
- Vendor, URL and lifetime are decided inside the rule. No test without MySQL.
- Choose when
- A script that you throw away.
WorksAsk a container: container.resolve('database')
- How
- A service locator. Classes can be swapped in the setup.
- Limit
- The constructor hides the need. A wrong string fails at run time. Every class depends on the container.
- Choose when
- A framework gives you no constructor.
StrongConstructor injection of a small interface
- How
OrderService(store, notifier), wired in one place by hand or by a container that only the root knows.- Limit
- Long constructors show up. That is a message: the class does too much.
- Choose when
- The default.
Events: loose, not free
One event, three listeners
A new listener is added without touching the service. But the event itself is now shared: its fields, its meaning, its time. And the flow is no longer visible in one place. Django's documentation warns about its signals: they “give the appearance of loose coupling”, and it recommends direct calls where possible.
Direct call or event?
| Direct call through an interface | Event | |
|---|---|---|
| Sender needs a result | yes | awkward |
| Order of effects | visible in the code | depends on subscription or delivery |
| One listener fails | sender sees it | must be designed |
| New reaction | edit the sender or a list | subscribe |
| Find out what happens | click through | search for subscribers |
| Good for | steps that belong to the action | reactions that the action does not depend on |
Coupling you do not see in imports
Order of calls
open()must come beforeread(). Let the constructor or awithblock do it.Meaning of values
Status 3 means paid, in both programs. Share an enum.
Same algorithm twice
Client and server both round a price. If one changes, totals differ.
Shared table
Two modules write the same rows. The schema is a global variable.
Time
Works only if the other answers within a second. Set a timeout and a plan B.
Inheritance
A subclass knows the inside of its parent. Prefer composition.
When a tight tie is right
Inside one small class or one module, methods may know each other well. That is cohesion. A Cart and its CartLine are coupled on purpose. An interface with a single implementation, no second one in sight and no test that needs it, is a longer way to the same place. See YAGNI.
Strength, distance, change
Summary
The whole topic in one minute.
Coupling is shared knowledge. Reduce it by sharing less (values instead of globals and flags), by sharing something stable (a small interface owned by its user), and by naming what is shared (a versioned event instead of a hidden table).
Concrete classes meet in a composition root. Events are useful when many react or when time may pass, and they move the coupling into the message. Strong ties inside one module are cohesion and need no cure.
- Coupling: if I change this, who else must change?
- Content, common, control, stamp, data, message: each step shares less.
- Pass needs in through the constructor, choose classes in one root.
- Interfaces belong to their user and speak the user's words.
- Events hide the receiver, not the meaning of the message.
- Strong and near is cohesion. Strong, far and changing is the problem.