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

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

  1. 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.

  2. 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.

  3. 2004

    Martin Fowler's article on containers names Dependency Injection and compares it with the Service Locator. It is dated 23 January 2004.

  4. 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.

Step 1 of 5

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.

Kites tied together

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.

KindGradeWhat is sharedExampleFirst step down
Contentworstthe inside: one part changes another's dataorder.service._cache.clear()private state and a method, see Ensuring proper encapsulation
Commonbadglobal data that many parts writeCONFIG['db'] = xpass the value in
Controlmoderatea flag that steers the other's logicsave(order, True)two methods, or a strategy object
Stampacceptablea whole structure of which a part is usedsendMail(order) needs only the addresspass the fields, or a small type
Datagoodonly the values neededsendMail(to, text)stay here for plain calls
Messageloosea message or event that both agreed onpublish(OrderPlaced)use it when many listen or time may pass
Grades are about how much is known, not about good and evil. Data coupling is the right answer more often than events.
Python
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")
Edit and run it in your browser

The bad shape and the good shape

Tight: the service builds its tools

OrderService- db: MySQLDatabase- email: SmtpEmailSender+ processOrder(order)

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

OrderService- store: OrderStore- notifier: Notifier+ place(order): bool«interface»OrderStore+ save(order)«interface»Notifier+ send(to, text)

1/3Needs, as interfaces

The service owns two small interfaces, in its own words: save an order, send a text.

usesimplements

The interface belongs to its user. This is the dependency inversion principle.

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

  • new inside 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 interfaceEvent
Sender needs a resultyesawkward
Order of effectsvisible in the codedepends on subscription or delivery
One listener failssender sees itmust be designed
New reactionedit the sender or a listsubscribe
Find out what happensclick throughsearch for subscribers
Good forsteps that belong to the actionreactions that the action does not depend on

Coupling you do not see in imports

  • Order of calls

    open() must come before read(). Let the constructor or a with block 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

Two ways out: make the tie weaker, or make the distance shorter.

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.

Sources