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.
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.
Press Run (⌘ Enter) to see what happens.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.
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.
pricing module is imported by 6 modules and itself imports 2. What is its instability, and what does it suggest?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:
| Form | The two sides must agree on | Example | Weaker alternative |
|---|---|---|---|
| Name | A name | Calling charge() | Already the weakest |
| Type | A type | Passing a Money, not a float | Fine, and type checkers catch it |
| Meaning | What a value means | -1 means "no limit"; "pd" means paid | A named constant or enum |
| Position | Argument order | ship(order, True, False, 3) | Keyword arguments or an object |
| Algorithm | The same algorithm | Client and server both hash a token the same way | One shared function |
| Execution | Order of calls | connect() must run before query() | An object that cannot exist unconnected |
| Timing | When things happen | A cache entry must be written before a webhook arrives | Explicit sequencing or idempotent retries |
| Value | Values that must change together | A price in the DB and the same price in a config file | One source of truth |
| Identity | The same object instance | Two services must hold the same in-memory session | Pass 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 each piece of code to the form of connascence it shows.
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.
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:
- 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.
- Invert one edge with an interface.
billingdefines aProtocolor interface for what it needs ("something that can give me an order total") andordersimplements it. The import arrow flips, which is dependency inversion from the SOLID lesson. - Replace the call with an event.
orderspublishesOrderPlaced.billingsubscribes.ordersno longer knowsbillingexists. - 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.
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)])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:
[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:
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.
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.
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?- 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.