Coupling and Cohesion in Software Engineering: Types and Examples

Raghav Chamadiya10 min read
On this page

Coupling and cohesion are two measures of software design: cohesion is how closely the elements inside one module belong together, and coupling is how strongly one module depends on others. Good design aims for high cohesion and low coupling, so each module has one clear job and changes without forcing changes elsewhere.

This guide covers what coupling and cohesion are, the classic types of each, why high cohesion and low coupling matter, how to measure coupling in a real codebase, the coupling you cannot see in imports, and how to find the most coupled files in your repository.

What are coupling and cohesion?

Cohesion looks inside a module; coupling looks between modules. A module here can be a function, a class, a file, a package or a service. The ideas apply at every level.

  • Cohesion asks: do the parts of this module work toward one purpose? A PasswordHasher class whose methods all hash and verify passwords is highly cohesive. A Utils file holding date formatting, HTTP retries and CSV parsing has low cohesion.
  • Coupling asks: how much does this module need to know about other modules to work? A function that takes two numbers and returns their sum is loosely coupled. A function that reaches into another class's private fields and depends on the order its methods are called is tightly coupled.

The two pull in the same direction. When a module has low cohesion, other code tends to depend on scattered parts of it, which raises coupling. When responsibilities are grouped well, each module exposes a small interface and the dependencies between modules shrink.

The terms were published by W. P. Stevens, Glenford Myers and Larry Constantine in "Structured Design" (IBM Systems Journal, 1974), and became standard through Yourdon and Constantine's 1979 book of the same name.

Types of coupling

The classic list ranks coupling from tightest (worst) to loosest (best). The names are old, but every one has a modern equivalent.

TypeWhat it meansModern example
Content couplingOne module reaches into another's internals or changes its codeMonkey-patching another module's function; reading a class's private fields
Common couplingModules share global dataA mutable global config dict read and written across the app
External couplingModules share an externally imposed format or deviceTwo services both parsing the same vendor file format
Control couplingOne module passes a flag that tells another what to dorender(data, mode="pdf") with a big if mode == inside
Stamp couplingModules pass a whole data structure when only part is usedPassing the full User object to a function that needs only user.email
Data couplingModules share only the plain data they need, through parameterssend_email(address, subject, body)

Scroll the table sideways to see every column.

Data coupling is the goal, not zero coupling. Modules have to talk to each other; the aim is that they do it through narrow, explicit interfaces.

Types of cohesion

Cohesion is ranked the other way, from weakest (worst) to strongest (best).

TypeWhy the parts are groupedExample
CoincidentalNo reason at allhelpers.py with unrelated functions
LogicalThey are the same kind of thingOne handle_input() that handles keyboard, mouse and network input by flag
TemporalThey run at the same timeAn init() that opens the database, loads config and starts a metrics thread
ProceduralThey run in a fixed orderSteps of one workflow that do not share data
CommunicationalThey work on the same dataFunctions that all read and update one Order record
SequentialThe output of one is the input of the nextParse, then validate, then transform, in one pipeline
FunctionalEvery part contributes to one well-defined taskhash_password() and verify_password() in a PasswordHasher

Scroll the table sideways to see every column.

Note the name collision: temporal cohesion in this table means grouping code because it runs at the same moment. Temporal coupling in the change-history sense, covered below, means files that change at the same moment. They are different ideas.

Why high cohesion and low coupling?

High cohesion and low coupling make change local: you edit one module, test it, and nothing else breaks. That is the whole payoff, and it shows up in review time, test time and bug rates.

Here is a small example. This function mixes concerns and depends on global state:

python
CONFIG = {}  # global, written elsewhere

def process_signup(form):
    if "@" not in form["email"]:
        raise ValueError("bad email")
    conn = psycopg.connect(CONFIG["dsn"])                    # common coupling: global config
    conn.execute("INSERT INTO users (email) VALUES (%s)", [form["email"]])
    smtp = smtplib.SMTP(CONFIG["smtp_host"])
    smtp.sendmail("hi@example.com", form["email"], "Welcome!")
    if CONFIG.get("mode") == "beta":                         # control coupling: behavior by flag
        add_to_beta_list(form["email"])

Every change to the database, the email provider or the beta program edits this one function, and testing it needs a database, a mail server and the right global config. After splitting it:

python
def process_signup(email: str, users: UserRepo, mailer: Mailer, beta: BetaProgram) -> None:
    validate_email(email)
    users.add(email)
    mailer.send_welcome(email)
    beta.enroll_if_open(email)

Each collaborator now has one job (functional cohesion), and the function depends only on the narrow interfaces it is given (data coupling). A test passes in fakes; a new email provider is a new Mailer, not an edit here.

Is low coupling always better? No. Splitting code that always changes together into separate modules adds indirection without adding independence. If two modules must change in lockstep every time, they are one module in two files, and merging them can be the right fix.

How to measure coupling

Count the dependencies. Coupling at the file or module level is measured from the import graph, with three standard numbers:

MetricWhat it countsWhat a high value means
Fan-in (afferent coupling, Ca)Modules that depend on this oneMany things break if it changes; it needs to be stable and well tested
Fan-out (efferent coupling, Ce)Modules this one depends onIt breaks when any of those change; often a sign of low cohesion
Instability, I = Ce / (Ca + Ce)Robert C. Martin's ratio, from 0 to 1Near 0: stable, many dependents. Near 1: unstable, depends on others but nothing depends on it

Scroll the table sideways to see every column.

Martin's guideline is that dependencies should point toward stability: an unstable module may depend on a stable one, but a widely used, stable module should not depend on a volatile one. Cohesion inside classes is measured with LCOM (lack of cohesion of methods), from Chidamber and Kemerer's 1994 metrics suite, which is based on how many pairs of methods in a class use no fields in common.

We measured the import graph of 195 popular open-source repositories (1,000+ GitHub stars each, 253,688 production source files, November 2026). The typical file is modestly coupled, but a few files carry a large share:

  • The median production file has 3.0 import edges.
  • In the median repo, the single most-imported file (the hub) is imported by 20% of all production files.
  • In 68 repos (35%), one file is imported by a quarter or more of the codebase.
  • The top 1% of files receive 17% of all import edges in the median repo.

Named examples: in grafana/grafana, packages/grafana-data/src/index.ts is imported by 3,178 of 10,090 production files (31%); in keycloak/keycloak, KeycloakSession.java by 1,690 of 6,626 (26%); in docker/compose, pkg/api/context.go by 130 of 194 (67%). A hub is not a defect. A shared type package or core interface is supposed to have high fan-in. It does mean that file needs the most stable interface and the most careful review, because every change to it reaches a fifth or more of the codebase.

Cycles are the other coupling signal: files that import each other, directly or through a chain. 89% of the same 195 repos have at least one circular import chain between files, and in the median repo 9.2% of production files sit inside one. Find circular dependencies in a monorepo shows how to break them.

Coupling you cannot see in imports: temporal coupling

Temporal coupling, also called change coupling or logical coupling, is two files that keep changing in the same commits. Sometimes there is an import between them and the co-change is expected. Often there is none: a backend handler and the frontend client that calls it, a database schema and the migration and fixture that mirror it, a config key and the docs that describe it.

These ties are invisible in the code and in every import-based metric above. They show up only in git history, and they cause a specific bug: someone changes one side, the other side is not in the pull request, and the mismatch ships.

You can find candidates with plain git:

bash
# commits touching a file, then the files that most often change alongside it
git log --format=%H -- src/api/orders.py | while read c; do git show --name-only --format= "$c"; done \
  | grep -v '^src/api/orders.py$' | sort | uniq -c | sort -rn | head -10

The useful part is the filtering: skip merge commits and huge commits, and require a minimum share of commits as well as a minimum count. Hidden coupling and co-change detection walks through the method, and the glossary entry on temporal coupling has the short definition.

How to find the most coupled files in your repo

repowise measures both kinds of coupling from one index: structural coupling from the parsed import and call graph, and temporal coupling from git history. It keeps the two families apart, so a shared commit never appears as an import, and labels each co-change pair by whether the graph explains it.

bash
repowise init                  # parses the graph and reads git history once
repowise risk main..HEAD       # for a change: files that depend on it, and co-change partners missing from the diff
Change coupling view in repowise showing call_resolver.py in the repowise repository with the files that change alongside it
Change coupling view in repowise showing call_resolver.py in the repowise repository with the files that change alongside it

The Coupling view on the repowise repository: one file traced to the files that move with it. Line opacity is strength.

  • Hub files and fan-in. The architecture view and the dependency graph show which files the most code depends on, and get_context returns a file's dependents and dependencies for an agent.
  • Co-change pairs. get_context and get_risk return each file's co_change_partners with how many commits they share and has_import_link, so the hidden ones are one filter away. The code-health layer flags strong hidden pairs as findings.
  • Missing partners in review. repowise risk, get_risk and the repowise bot name the files that historically change with a pull request but are not in it.
  • Low cohesion and god classes. The code-health detectors list low cohesion and score god classes, ranked by how often the file changes. See what is a god class for detection and how to split one.

Open the FastAPI coupling map to see it on a real repository. The architecture and git intelligence feature pages cover the graph and the history side. For what tight coupling looks like when it gets out of hand, see spaghetti code.

FAQ

What is coupling in programming?
Coupling is the degree to which one module depends on another: how much it needs to know about the other's data, behavior or internals to work. Loose coupling means modules talk through small, explicit interfaces, so one can change without forcing changes in the other. Tight coupling means a change in one ripples into many.
What is high cohesion?
High cohesion means every part of a module serves one well-defined purpose, so the module has a single reason to change. A class whose methods all operate on the same data toward the same task is highly cohesive; a utilities file of unrelated helpers is not.
Is low coupling always better?
Not always. Some coupling is required, since modules must exchange data, and the goal is narrow, explicit dependencies, not zero dependencies. Splitting code that always changes together into separate modules adds indirection without independence; when two modules change in lockstep every time, merging them can be the better design.
What is temporal coupling?
In change-history analysis, temporal coupling (also called change coupling) is two files that repeatedly change in the same commits, often with no import between them. It reveals hidden dependencies, such as an API and its client, that static analysis cannot see. In Constantine's cohesion list, "temporal cohesion" is a different idea: code grouped because it runs at the same time.
What is a god class?
A god class is a class that knows or does too much: many fields, many methods and many unrelated responsibilities, usually with high fan-in because so much of the codebase depends on it. It is the extreme of low cohesion and high coupling. The usual fix is Extract Class along the groups of fields and methods that are used together; see our guide to code smells.
What is the difference between coupling and cohesion?
Cohesion is measured inside a module and describes how well its parts belong together. Coupling is measured between modules and describes how much they depend on each other. High cohesion within modules usually leads to low coupling between them, which is why the two are always taught as a pair.