Skip to content

Lesson 9 of 28Keeping code healthy

Coupling, Cohesion, and Dependency Rules

Measure how tangled modules are, break import cycles, enforce boundaries in CI, and treat third-party packages as architecture.

18 min read0/4 questions

You rename one field on User and fourteen files fail to compile, including the PDF exporter and a cron job you have never heard of. Or the service will not even start, because orders imports billing which imports orders. Or a routine npm install pulls in a compromised version of a package five levels deep in your tree. All three are the same problem: dependencies nobody chose on purpose. This lesson gives you the vocabulary to talk about them precisely, numbers to measure them, and tools that stop them from creeping back in.

Cohesion and coupling, concretely

Cohesion is how strongly the things inside a module belong together. Coupling is how much modules depend on each other. You want high cohesion and low coupling, and the two are linked: when related code is scattered, the pieces must talk to each other constantly, which is coupling.

A concrete test: list the reasons a module might change. An invoicing package that holds invoice numbering, tax calculation and the invoice PDF template changes when invoicing rules change. That is high cohesion: one reason, many parts. A helpers.py that holds date parsing, a Slack client and a currency table changes for every reason in the company. That is low cohesion, and it drags coupling along, because every module imports helpers for one function and gets a dependency on all of it.

Coupling is not evil. A system with zero coupling does nothing. The goal is that dependencies are few, visible, in the right direction, and on stable things.

Measuring it: fan-in, fan-out and instability

Robert C. Martin defined three simple numbers per module (in Agile Software Development, 2002):

  • Afferent coupling (Ca): how many modules depend on this one. Fan-in.
  • Efferent coupling (Ce): how many modules this one depends on. Fan-out.
  • Instability: I = Ce / (Ca + Ce), from 0 to 1.

A module with I = 0 has many dependents and no dependencies. It is hard to change (everything breaks) but has no reason to change because of others. That is "stable". A module with I = 1 depends on others and nothing depends on it, like an HTTP route file. It is easy to change and changes often. Both are fine. The trouble is when they point the wrong way.

The stable dependencies principle says: depend in the direction of stability. A module should only depend on modules more stable than itself. The acyclic dependencies principle says: the module graph must have no cycles. Here is a small service, scored.

Python
# Who imports whom, as you would extract it from `import` statements.IMPORTS = { "api": ["orders", "billing", "auth"], "orders": ["domain", "db", "billing"], "billing": ["domain", "db", "stripe_client", "orders"], # <- suspicious "auth": ["db"], "domain": [], "db": ["domain"], "stripe_client": [],} def metrics(graph): fan_in = {m: 0 for m in graph} for deps in graph.values(): for d in deps: fan_in[d] += 1 rows = [] for m, deps in graph.items(): ca, ce = fan_in[m], len(deps) # afferent (in), efferent (out) inst = ce / (ca + ce) if ca + ce else 0.0 rows.append((m, ca, ce, round(inst, 2))) return sorted(rows, key=lambda r: r[3]) def find_cycles(graph): cycles, state, stack = [], {}, [] def visit(m): state[m] = "open" stack.append(m) for d in graph[m]: if state.get(d) == "open": cycles.append(stack[stack.index(d):] + [d]) elif d not in state: visit(d) stack.pop() state[m] = "done" for m in graph: if m not in state: visit(m) return cycles print(f"{'module':<14}{'Ca':>4}{'Ce':>4}{'I':>6}")for m, ca, ce, i in metrics(IMPORTS): print(f"{m:<14}{ca:>4}{ce:>4}{i:>6}") print("cycles:", find_cycles(IMPORTS)) # Stable dependencies principle: I should not rise along an edge.I = {m: i for m, _, _, i in metrics(IMPORTS)}for m, deps in IMPORTS.items(): for d in deps: if I[d] > I[m]: print(f"SDP violation: {m} (I={I[m]}) depends on less stable {d} (I={I[d]})")
Output
Press Run (⌘ Enter) to see what happens.
The same graph, read for direction
apiordersbillingauthdbvendordomainI=0

currentwaitingdone

domain has three dependents and imports nothing. It is the most stable module, which is right: business rules should not move when the database or the web layer does.

1/4

These metrics are a flashlight, not a grade. Use them to find modules worth a closer look, such as a "stable" module that changes every week (it is a hotspot that everything depends on) or a cycle hiding in a big graph. Tools compute them for you: pydeps and import-linter for Python, dependency-cruiser and madge for TypeScript.

Quick check
A pricing module is imported by 6 modules and itself imports 2. What is its instability, and what does it suggest?
Need a nudge? A hint rules out a wrong answer.

Connascence: a finer vocabulary for "how coupled"

"These are tightly coupled" is vague. Connascence (Meilir Page-Jones, 1990s, made popular again by Jim Weirich) names what two pieces of code must agree on, so that if one changes, the other must too. The forms run from weakest to strongest:

FormThe two sides must agree onExampleWeaker alternative
NameA nameCalling charge()Already the weakest
TypeA typePassing a Money, not a floatFine, and type checkers catch it
MeaningWhat a value means-1 means "no limit"; "pd" means paidA named constant or enum
PositionArgument ordership(order, True, False, 3)Keyword arguments or an object
AlgorithmThe same algorithmClient and server both hash a token the same wayOne shared function
ExecutionOrder of callsconnect() must run before query()An object that cannot exist unconnected
TimingWhen things happenA cache entry must be written before a webhook arrivesExplicit sequencing or idempotent retries
ValueValues that must change togetherA price in the DB and the same price in a config fileOne source of truth
IdentityThe same object instanceTwo services must hold the same in-memory sessionPass IDs, not shared objects

The first five are static (visible in source). The last four are dynamic (only visible at run time), which makes them more dangerous: no compiler or linter will tell you.

Three dimensions decide how much a given connascence matters. Strength is the form above. Locality: strong connascence inside one function is fine, across two services it is a liability. Degree: two places agreeing is manageable, forty is not. The practical rule follows: convert strong forms into weaker ones, and the further apart two pieces of code are, the weaker their connascence should be.

Match the pairs0/5 matched

Match each piece of code to the form of connascence it shows.

Choose an item, then its match on the other side.

Import cycles, and how to break them

A cycle means two modules cannot be understood, tested or deployed separately. They are one module wearing two names. Cycles also fail in concrete ways.

In Python, import runs the module top to bottom. If orders starts importing billing, and billing asks for a name from orders that has not been defined yet, Python finds a half-built module and raises an ImportError. Whether it fails depends on which module is imported first and where each name sits in the file, so the bug can appear when someone merely reorders imports.

Python
import os, sys, tempfile, textwrap, importlibsys.dont_write_bytecode = True pkg = tempfile.mkdtemp()sys.path.insert(0, pkg) def write(files: dict[str, str]) -> None: for name, src in files.items(): with open(os.path.join(pkg, name), "w") as f: f.write(textwrap.dedent(src)) for mod in ("orders", "billing", "money"): sys.modules.pop(mod, None) importlib.invalidate_caches() # ---- BEFORE: orders and billing import each otherwrite({ "orders.py": """ from billing import charge # runs billing.py top to bottom first def place_order(total): return charge(total) DEFAULT_CURRENCY = "GBP" """, "billing.py": """ from orders import DEFAULT_CURRENCY # orders is only half-built right now def charge(total): return f"charged {total} {DEFAULT_CURRENCY}" """,})try: import ordersexcept ImportError as e: print("before:", str(e).split(" (/")[0]) # ---- AFTER: the shared fact moves to a module both can depend onwrite({ "money.py": """ DEFAULT_CURRENCY = "GBP" """, "orders.py": """ from billing import charge def place_order(total): return charge(total) """, "billing.py": """ from money import DEFAULT_CURRENCY def charge(total): return f"charged {total} {DEFAULT_CURRENCY}" """,})import ordersprint("after: ", orders.place_order(40))
Output
Press Run (⌘ Enter) to see what happens.

In TypeScript with ES modules, imports are hoisted and bindings are live, so a cycle often works by luck. It fails when one module uses an imported value during its own top-level evaluation, before the other module has run: class Admin extends User at the top of a file is the classic case, and you get ReferenceError: Cannot access 'User' before initialization. Cycles also confuse bundlers and hot reload, and they make code splitting pull in far more than you asked for.

There are four ways out, from most to least preferred:

  1. Extract the shared part. What both modules need (a type, a constant, a small rule) moves to a third, lower module. That is what fixed the example.
  2. Invert one edge with an interface. billing defines a Protocol or interface for what it needs ("something that can give me an order total") and orders implements it. The import arrow flips, which is dependency inversion from the SOLID lesson.
  3. Replace the call with an event. orders publishes OrderPlaced. billing subscribes. orders no longer knows billing exists.
  4. Merge them. If the two really change together every time, they were one module. Admitting it is a valid fix.

A function-level import inside a function body also makes the error go away. It does not remove the cycle, it hides it. Use it as a temporary bandage with a ticket attached, never as the fix.

Predict the outputPython

What does this print?

graph = {"a": ["b"], "b": ["c"], "c": ["a", "d"], "d": []}

def has_path(src, dst, seen=()):
  for n in graph[src]:
      if n == dst or (n not in seen and has_path(n, dst, seen + (n,))):
          return True
  return False

print([m for m in graph if has_path(m, m)])
Need a nudge? Hints walk you through it.

Enforce boundaries in CI, not in code review

Architecture diagrams in a wiki do not stop a tired engineer from importing the database client into the domain layer at 6pm. A failing CI check does. Every mainstream stack has a tool that reads your imports and fails the build when a rule breaks.

For Python, import-linter reads contracts from pyproject.toml and runs as lint-imports:

pyproject.toml
[tool.importlinter]
root_package = "shop"
include_external_packages = true
 
[[tool.importlinter.contracts]]
name = "Layers only point down"
type = "layers"
layers = ["shop.api", "shop.services", "shop.domain"]
 
[[tool.importlinter.contracts]]
name = "Domain does not touch infrastructure or frameworks"
type = "forbidden"
source_modules = ["shop.domain"]
forbidden_modules = ["shop.infrastructure", "fastapi", "sqlalchemy"]

The layers contract lets higher layers import lower ones but not the reverse. The forbidden contract is the one that keeps the domain pure.

For TypeScript, dependency-cruiser does the same with path rules, and also catches cycles:

.dependency-cruiser.cjs
module.exports = {
  forbidden: [
    {
      name: "domain-not-to-infrastructure",
      severity: "error",
      from: { path: "^src/domain" },
      to: { path: "^src/(infrastructure|app)" },
    },
    { name: "no-circular", severity: "error", from: {}, to: { circular: true } },
  ],
};

Run it with npx depcruise src --config .dependency-cruiser.cjs. If you only need a quick rule, ESLint's built-in no-restricted-imports can forbid import patterns for files under src/domain/**, and eslint-plugin-boundaries gives you element types and allowed directions. In an Nx monorepo, the @nx/enforce-module-boundaries rule does it with project tags. Pick one, add it to CI, and treat a violation like a failing test.

Third-party packages are architecture

Every package you install is a dependency you do not control: its API, its release schedule, its bugs, its licence, and its security. Treat adding one as a design decision.

Wrap volatile vendors behind your own interface. A payment provider, an email service or an LLM SDK will change on their schedule, not yours. Define the interface in your words, and let exactly one adapter file import the vendor. The domain sees ChargeResult, never the vendor's response object. You met this shape as the Adapter in Structural Patterns, and Hexagonal and Clean Architecture later builds a whole design on it; here is the coupling payoff.

TypeScript
// The vendor SDK's shapes (imagine these come from node_modules and change every major).type VendorChargeResponse = { id: string; status: "succeeded" | "requires_action" | "failed"; amount_received: number };const vendorSdk = { charges: { create: (p: { amount: number; currency: string; source: string }): VendorChargeResponse => p.source === "tok_declined" ? { id: "ch_2", status: "failed", amount_received: 0 } : { id: "ch_1", status: "succeeded", amount_received: p.amount }, },}; // YOUR interface, in your words. The domain only ever sees this.type ChargeResult = { kind: "paid"; reference: string } | { kind: "declined" } | { kind: "needs_3ds" };interface PaymentGateway { charge(amountCents: number, currency: "GBP" | "EUR", cardToken: string): ChargeResult;} // The adapter is the ONLY file that imports the vendor. A vendor upgrade edits one file.class VendorGateway implements PaymentGateway { charge(amountCents: number, currency: "GBP" | "EUR", cardToken: string): ChargeResult { const r = vendorSdk.charges.create({ amount: amountCents, currency: currency.toLowerCase(), source: cardToken }); if (r.status === "succeeded") return { kind: "paid", reference: r.id }; if (r.status === "requires_action") return { kind: "needs_3ds" }; return { kind: "declined" }; }} // Tests and local dev use a fake with the same contract. No network, no keys.class FakeGateway implements PaymentGateway { calls: number[] = []; charge(amountCents: number): ChargeResult { this.calls.push(amountCents); return amountCents > 100_000 ? { kind: "declined" } : { kind: "paid", reference: "fake-1" }; }} function checkout(gateway: PaymentGateway, totalCents: number, token: string): string { const result = gateway.charge(totalCents, "GBP", token); switch (result.kind) { case "paid": return `order confirmed (${result.reference})`; case "needs_3ds": return "redirect to bank"; case "declined": return "card declined"; }} console.log(checkout(new VendorGateway(), 4999, "tok_visa"));console.log(checkout(new VendorGateway(), 4999, "tok_declined"));const fake = new FakeGateway();console.log(checkout(fake, 250_000, "anything"), fake.calls);
Output
Press Run (⌘ Enter) to see what happens.

Do not wrap everything. Wrapping your web framework or your standard library just adds a layer to maintain. Wrap what is volatile (changes often, might be swapped) or critical (money, auth, data you cannot lose).

Evaluate before you install. Check maintenance (recent releases, issues answered, more than one maintainer), licence (MIT, Apache 2.0 and BSD are usually fine for commercial use; GPL and AGPL need a conversation with legal), size (on the frontend, bundle size is user-facing latency), and transitive dependencies (a 20-line helper that pulls in 40 packages is 40 more chances to be compromised). Sometimes the right answer is to copy 20 lines with credit.

Pin and update on purpose. Semver ranges decide what you get on a fresh install: ^1.4.2 allows anything below 2.0.0, ~1.4.2 allows only patch releases below 1.5.0, and ^0.4.2 allows only below 0.5.0 because pre-1.0 minors may break. The lockfile (package-lock.json, pnpm-lock.yaml, uv.lock) records exact versions so every machine and CI run installs the same tree. Commit it, and use npm ci or uv sync --locked in CI. Then let Renovate or Dependabot open small, regular upgrade PRs that your tests check, instead of a terrifying upgrade once a year.

Supply-chain hygiene. In September 2025, attackers phished an npm maintainer and published malicious versions of extremely popular packages such as chalk and debug. Days later the self-replicating Shai-Hulud worm used stolen npm tokens to publish infected versions of hundreds more packages, and a second wave followed in November. Teams with lockfiles, delayed updates and CI audits were largely fine. The habits: run npm audit or pip-audit in CI, prefer packages published with provenance or trusted publishing, consider a minimum release age so brand-new versions wait a few days before you adopt them (Renovate and recent pnpm versions support this; check their docs for the setting), and keep install scripts and CI tokens on the shortest leash you can.

The shared utils trap

Every codebase grows a common, shared, utils or core package. It starts with one date helper. Two years later it holds 3,000 lines, every module imports it, and it imports the database client, the config loader and a logging setup. Its instability is near zero, so nobody dares change it, and its cohesion is near zero, so it changes constantly anyway. It has become a coupling hub: changing it rebuilds and retests everything.

Defences: put a helper next to its only user until a second user appears (the rule of three applies to modules too). Name shared modules by what they hold (money, dates, http_errors), never by the fact that they are shared. Forbid shared modules from importing application code, so they stay at the bottom of the graph. And when a shared module serves one domain, move it into that domain.

Quick check
Your package.json says "date-lib": "^0.9.3" and there is no lockfile. Version 0.10.0 is published with a breaking change. What does a fresh npm install give you?
Need a nudge? A hint rules out a wrong answer.
Key terms
cohesion
How strongly the parts of one module belong together; high cohesion means one reason to change.
coupling
How much modules depend on each other, so that a change in one forces a change in another.
instability
Ce / (Ca + Ce): the share of a module's couplings that are outgoing. 0 is stable, 1 is unstable.
stable dependencies principle
Depend in the direction of stability: on modules at least as stable as yourself.
connascence
Two pieces of code that must change together, classified by form, strength, locality and degree.
import cycle
Modules that import each other directly or indirectly, so neither can stand alone.
lockfile
A committed file recording the exact version of every direct and transitive dependency.