Cohesion, Coupling & the Law of Demeter
Before SOLID, before design patterns, there were two words: cohesion and coupling. Larry Constantine introduced them in the late 1960s, and Ed Yourdon and Constantine set them out in Structured Design (1979). They described modules and subroutines, not classes, but they've outlived nearly every other idea from that era because they measure something real: how hard is it to change one part of the system without touching the others?
- Cohesion is about what's inside a unit: do its parts belong together?
- Coupling is about what's between units: how much does one depend on another?
The goal is the familiar slogan, high cohesion, low coupling. Most other principles are refinements of it. Single Responsibility is a statement about cohesion. Dependency Inversion and Interface Segregation are statements about coupling. This page gives you the vocabulary underneath them: the kinds of cohesion and coupling, connascence as a sharper way to talk about coupling, the Law of Demeter and its train wrecks, and tell-don't-ask.
Every sample was run with Java 24, Python 3.12 and TypeScript 5.8 (tsc --strict, then tsx). Java samples use a small check helper so they fail without the -ea flag.
1. Why these two measures matter
Every change to software starts in one place and spreads. Cohesion and coupling describe how far it spreads.
flowchart LR
subgraph lowCoh["Low cohesion, high coupling"]
A1["Class A: pricing + email + stock"] --- B1["Class B"]
A1 --- C1["Class C"]
B1 --- C1
C1 --- D1["Class D"]
A1 --- D1
end
subgraph highCoh["High cohesion, low coupling"]
P["Pricing"] --> I["Interface"]
M["Mailer"]
S["Stock"] --> I
end
- When cohesion is high, a change in one concept lands in one class. You open one file, change it, test it.
- When coupling is low, that class's neighbours don't notice, because they depend on a narrow, stable interface rather than its internals.
- When cohesion is low, one concept is smeared across several classes, or one class holds several concepts. Either way, a change touches more than it should.
- When coupling is high, a change ripples. You fix pricing and break the email template, because the mailer reached into a pricing field.
These aren't independent. Low cohesion causes coupling: if a concept is split across three classes, those three must know about each other to work. Fixing cohesion usually reduces coupling for free.
2. Cohesion
Cohesion asks: do the things in this unit belong together, and for a good reason? Constantine and Yourdon ranked the reasons from worst to best. The names are old, but you'll recognise every one of them in modern code.
| Kind (worst to best) | Parts are together because… | Modern example |
|---|---|---|
| Coincidental | No reason: they had to go somewhere | Utils, Helpers, Common, Misc |
| Logical | They're the same category of thing, chosen by a flag | InputHandler.handle(type, data) for keyboard, mouse and network |
| Temporal | They happen at the same time | onStartup() that opens the DB, warms the cache and sends a metrics ping |
| Procedural | They happen in a sequence, but on different data | checkout() that validates the form, then logs analytics, then clears the UI |
| Communicational | They work on the same data | A CustomerReport with several methods all reading one customer record |
| Sequential | The output of one is the input of the next | A parse, then validate, then transform pipeline |
| Functional | They all contribute to one well-defined task | TaxCalculator, SeatAllocator, Money |
Aim for functional cohesion in domain classes. Communicational and sequential are fine for services and pipelines. The bottom three are smells.
2.1 Spotting low cohesion
The practical test is which methods use which fields. In a cohesive class, most methods use most fields. In a class with low cohesion, the methods split into groups that share nothing, and each group is really a separate class trying to get out. The metric family LCOM ("lack of cohesion of methods", from Chidamber and Kemerer, 1994) formalises this, but you can do it by eye.
Here's a class named after the system that holds three unrelated jobs. Draw the field-to-method lines and you get three disconnected islands.
| Method | smtpHost | taxBasisPoints | stock |
|---|---|---|---|
sendReceipt | ✔ | ||
taxFor | ✔ | ||
restock, reserve | ✔ |
import java.util.*;
// ---------- before: three islands of fields and methods in one class ----------
final class StoreManager {
private final String smtpHost;
private final int taxBasisPoints;
private final Map<String, Integer> stock = new HashMap<>();
StoreManager(String smtpHost, int taxBasisPoints) { this.smtpHost = smtpHost; this.taxBasisPoints = taxBasisPoints; }
String sendReceipt(String to, String body) { return smtpHost + " -> " + to + ": " + body; }
long taxFor(long cents) { return cents * taxBasisPoints / 10_000; }
void restock(String sku, int qty) { stock.merge(sku, qty, Integer::sum); }
boolean reserve(String sku, int qty) {
int have = stock.getOrDefault(sku, 0);
if (have < qty) return false;
stock.put(sku, have - qty);
return true;
}
}
// ---------- after: one class per island, each functionally cohesive ----------
final class ReceiptMailer {
private final String smtpHost;
ReceiptMailer(String smtpHost) { this.smtpHost = smtpHost; }
String send(String to, String body) { return smtpHost + " -> " + to + ": " + body; }
}
final class TaxPolicy {
private final int basisPoints;
TaxPolicy(int basisPoints) { this.basisPoints = basisPoints; }
long taxFor(long cents) { return cents * basisPoints / 10_000; }
}
final class Inventory {
private final Map<String, Integer> stock = new HashMap<>();
void restock(String sku, int qty) {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive");
stock.merge(sku, qty, Integer::sum);
}
boolean reserve(String sku, int qty) {
int have = stock.getOrDefault(sku, 0);
if (have < qty) return false;
stock.put(sku, have - qty);
return true;
}
int available(String sku) { return stock.getOrDefault(sku, 0); }
}
class CohesionDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
StoreManager god = new StoreManager("smtp.shop", 1_800);
check(god.taxFor(1_000) == 180, "before works, but everything is tangled");
Inventory inventory = new Inventory(); // testable without an SMTP host or a tax rate
inventory.restock("tea", 3);
check(inventory.reserve("tea", 2) && !inventory.reserve("tea", 2), "reserve respects stock");
check(inventory.available("tea") == 1, "one left");
check(new TaxPolicy(1_800).taxFor(1_000) == 180, "tax");
check(new ReceiptMailer("smtp.shop").send("ana", "hi").equals("smtp.shop -> ana: hi"), "mail");
System.out.println("three cohesive classes");
}
}
# ---------- before: three islands of fields and methods in one class ----------
class StoreManager:
def __init__(self, smtp_host: str, tax_basis_points: int) -> None:
self.smtp_host = smtp_host
self.tax_basis_points = tax_basis_points
self.stock: dict[str, int] = {}
def send_receipt(self, to: str, body: str) -> str:
return f"{self.smtp_host} -> {to}: {body}"
def tax_for(self, cents: int) -> int:
return cents * self.tax_basis_points // 10_000
def restock(self, sku: str, qty: int) -> None:
self.stock[sku] = self.stock.get(sku, 0) + qty
# ---------- after: one class per island, each functionally cohesive ----------
class ReceiptMailer:
def __init__(self, smtp_host: str) -> None:
self._host = smtp_host
def send(self, to: str, body: str) -> str:
return f"{self._host} -> {to}: {body}"
class TaxPolicy:
def __init__(self, basis_points: int) -> None:
self._bp = basis_points
def tax_for(self, cents: int) -> int:
return cents * self._bp // 10_000
class Inventory:
def __init__(self) -> None:
self._stock: dict[str, int] = {}
def restock(self, sku: str, qty: int) -> None:
if qty <= 0:
raise ValueError("qty must be positive")
self._stock[sku] = self._stock.get(sku, 0) + qty
def reserve(self, sku: str, qty: int) -> bool:
have = self._stock.get(sku, 0)
if have < qty:
return False
self._stock[sku] = have - qty
return True
def available(self, sku: str) -> int:
return self._stock.get(sku, 0)
assert StoreManager("smtp.shop", 1_800).tax_for(1_000) == 180
inventory = Inventory() # no SMTP host or tax rate needed to test it
inventory.restock("tea", 3)
assert inventory.reserve("tea", 2) and not inventory.reserve("tea", 2)
assert inventory.available("tea") == 1
assert TaxPolicy(1_800).tax_for(1_000) == 180
assert ReceiptMailer("smtp.shop").send("ana", "hi") == "smtp.shop -> ana: hi"
print("three cohesive classes")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: three islands of fields and methods in one class ----------
class StoreManager {
private readonly stock = new Map<string, number>();
constructor(private readonly smtpHost: string, private readonly taxBasisPoints: number) {}
sendReceipt(to: string, body: string): string { return `${this.smtpHost} -> ${to}: ${body}`; }
taxFor(cents: number): number { return Math.floor((cents * this.taxBasisPoints) / 10_000); }
restock(sku: string, qty: number): void { this.stock.set(sku, (this.stock.get(sku) ?? 0) + qty); }
}
// ---------- after: one class per island, each functionally cohesive ----------
class ReceiptMailer {
constructor(private readonly smtpHost: string) {}
send(to: string, body: string): string { return `${this.smtpHost} -> ${to}: ${body}`; }
}
class TaxPolicy {
constructor(private readonly basisPoints: number) {}
taxFor(cents: number): number { return Math.floor((cents * this.basisPoints) / 10_000); }
}
class Inventory {
private readonly stock = new Map<string, number>();
restock(sku: string, qty: number): void {
if (qty <= 0) throw new RangeError("qty must be positive");
this.stock.set(sku, this.available(sku) + qty);
}
reserve(sku: string, qty: number): boolean {
const have = this.available(sku);
if (have < qty) return false;
this.stock.set(sku, have - qty);
return true;
}
available(sku: string): number { return this.stock.get(sku) ?? 0; }
}
check(new StoreManager("smtp.shop", 1_800).taxFor(1_000) === 180, "before works but is tangled");
const inventory = new Inventory();
inventory.restock("tea", 3);
check(inventory.reserve("tea", 2) && !inventory.reserve("tea", 2), "reserve respects stock");
check(inventory.available("tea") === 1, "one left");
check(new TaxPolicy(1_800).taxFor(1_000) === 180, "tax");
check(new ReceiptMailer("smtp.shop").send("ana", "hi") === "smtp.shop -> ana: hi", "mail");
console.log("three cohesive classes");
The split also improves testing. To test reserve on the old class you had to supply an SMTP host and a tax rate, neither of which has anything to do with stock. That's a reliable symptom: if a test needs setup that's unrelated to what it's testing, the class under test has low cohesion.
2.2 Cohesion has a sweet spot
You can overdo it. Split a cohesive Money class into MoneyAdder, MoneyFormatter and MoneyComparator, and you've lowered cohesion, because the knowledge of how money works is now spread across three places that must change together. Functional cohesion means one concept per class, not one method per class. If two classes always change together and are always used together, they probably want to be one class.
3. Coupling
Coupling asks: how much must one unit know about another? Again there's a classic ranking, worst first. The modern equivalents are more useful than the names.
| Kind (worst to best) | A depends on B's… | Modern example |
|---|---|---|
| Content | Internals: private state or code | Reflection to set a private field, a subclass poking protected state, monkey-patching |
| Common (global) | Shared mutable global state | A static Config.discountRate that anyone can write |
| External | An externally imposed format or protocol | Two classes both parsing the same CSV layout by hand |
| Control | Flags that tell it what to do | ship(order, mode) where mode picks the algorithm |
| Stamp | A whole data structure, when it needs one field | cost(Order order) that only reads order.weight |
| Data | Simple parameters it actually needs | cost(int weightGrams) |
| Message | Only a message or interface, no shared data | Calling notifier.send(event) on an interface |
Some coupling is necessary. Objects that don't depend on anything do nothing useful. The aim is to push coupling down the table, and to make what remains point towards stable things.
3.1 Fixing control, common and stamp coupling
This shipping calculator has three problems at once. It reads a global surcharge that any code can change (common coupling). It takes an integer mode that selects the algorithm (control coupling). And it takes the whole order when it only needs the weight (stamp coupling).
// ---------- before: global state, a mode flag and the whole order ----------
final class Settings { static long expressSurchargeCents = 500; } // anyone can write this
record Order(String id, String customer, int weightGrams) {}
final class ShippingCalc {
static final int STANDARD = 0, EXPRESS = 1, PICKUP = 2;
long cost(Order order, int mode) {
long base = order.weightGrams() / 100 * 10L;
if (mode == EXPRESS) return base + Settings.expressSurchargeCents;
if (mode == PICKUP) return 0;
return base;
}
}
// ---------- after: data in, behaviour per option, no globals ----------
interface ShippingOption { long costCents(int weightGrams); }
record Standard() implements ShippingOption {
public long costCents(int weightGrams) { return weightGrams / 100 * 10L; }
}
record Express(long surchargeCents) implements ShippingOption {
public long costCents(int weightGrams) { return new Standard().costCents(weightGrams) + surchargeCents; }
}
record Pickup() implements ShippingOption {
public long costCents(int weightGrams) { return 0; }
}
class CouplingDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
Order order = new Order("o-1", "ana", 1_250);
ShippingCalc calc = new ShippingCalc();
check(calc.cost(order, ShippingCalc.EXPRESS) == 620, "before: 120 + 500");
Settings.expressSurchargeCents = 0; // some unrelated code "just for a test"
check(calc.cost(order, ShippingCalc.EXPRESS) == 120, "before: action at a distance");
check(calc.cost(order, 7) == 120, "before: an invalid mode silently means standard");
check(new Standard().costCents(1_250) == 120, "after: standard");
check(new Express(500).costCents(1_250) == 620, "after: express owns its surcharge");
check(new Pickup().costCents(1_250) == 0, "after: pickup");
System.out.println("no globals, no flags, only the data each option needs");
}
}
from dataclasses import dataclass
from typing import Protocol
# ---------- before: global state, a mode flag and the whole order ----------
class Settings:
express_surcharge_cents = 500 # anyone can write this
@dataclass(frozen=True)
class Order:
id: str
customer: str
weight_grams: int
STANDARD, EXPRESS, PICKUP = 0, 1, 2
def shipping_cost(order: Order, mode: int) -> int:
base = order.weight_grams // 100 * 10
if mode == EXPRESS:
return base + Settings.express_surcharge_cents
if mode == PICKUP:
return 0
return base
# ---------- after: data in, behaviour per option, no globals ----------
class ShippingOption(Protocol):
def cost_cents(self, weight_grams: int) -> int: ...
class Standard:
def cost_cents(self, weight_grams: int) -> int:
return weight_grams // 100 * 10
@dataclass(frozen=True)
class Express:
surcharge_cents: int
def cost_cents(self, weight_grams: int) -> int:
return Standard().cost_cents(weight_grams) + self.surcharge_cents
class Pickup:
def cost_cents(self, weight_grams: int) -> int:
return 0
order = Order("o-1", "ana", 1_250)
assert shipping_cost(order, EXPRESS) == 620
Settings.express_surcharge_cents = 0 # unrelated code changes global state
assert shipping_cost(order, EXPRESS) == 120 # action at a distance
assert shipping_cost(order, 7) == 120 # invalid mode silently means standard
options: list[ShippingOption] = [Standard(), Express(500), Pickup()]
assert [o.cost_cents(1_250) for o in options] == [120, 620, 0]
print("no globals, no flags, only the data each option needs")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: global state, a mode flag and the whole order ----------
const Settings = { expressSurchargeCents: 500 }; // anyone can write this
interface Order { id: string; customer: string; weightGrams: number }
function shippingCost(order: Order, mode: number): number {
const base = Math.floor(order.weightGrams / 100) * 10;
if (mode === 1) return base + Settings.expressSurchargeCents;
if (mode === 2) return 0;
return base;
}
// ---------- after: data in, behaviour per option, no globals ----------
interface ShippingOption { costCents(weightGrams: number): number }
const standard: ShippingOption = { costCents: (g) => Math.floor(g / 100) * 10 };
const express = (surchargeCents: number): ShippingOption => ({
costCents: (g) => standard.costCents(g) + surchargeCents,
});
const pickup: ShippingOption = { costCents: () => 0 };
const order: Order = { id: "o-1", customer: "ana", weightGrams: 1_250 };
check(shippingCost(order, 1) === 620, "before: 120 + 500");
Settings.expressSurchargeCents = 0;
check(shippingCost(order, 1) === 120, "before: action at a distance");
check(shippingCost(order, 7) === 120, "before: invalid mode means standard");
check([standard, express(500), pickup].map((o) => o.costCents(1_250)).join() === "120,620,0", "after");
console.log("no globals, no flags, only the data each option needs");
Each fix moves coupling down the table. The global becomes a constructor value owned by Express (common → data). The mode flag becomes polymorphism (control → message). The whole order becomes the one number the calculation needs (stamp → data), which also means the calculator can price a parcel that isn't an order at all.
Stamp coupling is a judgment call
Passing a whole object is sometimes the better choice. If a method needs four fields of Order, passing Order is clearer than four parameters, and the method may legitimately need more fields later. Stamp coupling hurts when the callee needs one trivial field and the dependency drags a big type into a module that otherwise wouldn't know about it.
3.2 Afferent, efferent and stable dependencies
For whole packages or modules, Robert C. Martin's metrics are a handy way to reason about direction:
- Afferent coupling (Ca): how many other modules depend on this one. High Ca means many callers will notice changes.
- Efferent coupling (Ce): how many modules this one depends on. High Ce means it breaks when they change.
- Instability: I = Ce / (Ca + Ce), from 0 (stable, everyone depends on it, it depends on nothing) to 1 (unstable, depends on lots, nobody depends on it).
The stable dependencies principle says dependencies should point towards stability: volatile code like UI and adapters should depend on stable code like domain models and interfaces, never the reverse. That's Dependency Inversion in metric form. In an LLD interview you won't compute these, but saying "the domain doesn't import the payment adapter, the adapter imports the domain" shows the same understanding.
4. Connascence: a sharper vocabulary
"Coupling" is a blunt word. Saying two classes are "tightly coupled" doesn't tell you how, or what to do about it. Meilir Page-Jones introduced connascence in 1992 (and expanded on it in What Every Programmer Should Know About Object-Oriented Design, 1995) to fill that gap. Jim Weirich's conference talks in the 2000s brought it to a wider audience.
Two pieces of code are connascent if changing one requires changing the other to keep the system correct. Page-Jones named the kinds, ordered from weakest (easiest to live with) to strongest.
| Kind | Two pieces must agree on… | Example |
|---|---|---|
| Static (visible in the source) | ||
| Name | The name of something | A caller and a method agree on calculateTotal |
| Type | The type of something | A caller passes an int where an int is expected |
| Meaning (convention) | What a value means | status == 2 means "shipped" in several places |
| Position | The order of values | createUser("ana", "ana@x.io", true, 3) |
| Algorithm | A particular algorithm | Client and server both compute the same checksum by hand |
| Dynamic (visible only at runtime) | ||
| Execution | The order of calls | connect() must be called before send() |
| Timing | When something happens | A timeout must exceed the retry interval |
| Value | Values that must stay consistent | rectangle.area must equal width × height after each update |
| Identity | Referring to the same object | Two components must share one cache instance |
Connascence has three dimensions, and together they make a useful rule:
- Strength: dynamic is stronger than static, and within each group, lower rows are stronger. Stronger kinds are harder to spot and to refactor.
- Locality: connascence between two lines in the same method is fine. The same connascence across two services is dangerous.
- Degree: how many places are involved. Two is manageable. Forty isn't.
The rule: convert strong connascence to weaker forms, and keep strong connascence local.
Most good refactorings are this rule applied. Replacing a magic number with a named constant or enum turns connascence of meaning into connascence of name. Replacing positional parameters with a parameter object or named arguments turns connascence of position into connascence of name. Extracting a duplicated algorithm into one function turns connascence of algorithm into connascence of name. That's DRY restated precisely.
4.1 From position and meaning to name and type
import java.util.*;
// ---------- before: connascence of position and meaning ----------
final class UserServiceBefore {
final List<String> created = new ArrayList<>();
// plan: 1 = free, 2 = premium, 3 = team. Every caller must remember the order and the codes.
void register(String username, String email, boolean marketing, int plan) {
created.add(username + "|" + email + "|" + marketing + "|" + plan);
}
}
// ---------- after: connascence of name and type ----------
enum Plan { FREE, PREMIUM, TEAM }
enum Marketing { OPT_IN, OPT_OUT }
record Email(String value) {
Email { if (!value.contains("@")) throw new IllegalArgumentException("not an email: " + value); }
}
record Registration(String username, Email email, Marketing marketing, Plan plan) {}
final class UserService {
final List<Registration> created = new ArrayList<>();
void register(Registration r) { created.add(r); }
}
class ConnascenceDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
UserServiceBefore before = new UserServiceBefore();
before.register("ana@x.io", "ana", true, 3); // arguments swapped, wrong plan code: compiles fine
check(before.created.get(0).startsWith("ana@x.io|ana"), "before: the mistake is silent");
UserService after = new UserService();
after.register(new Registration("ana", new Email("ana@x.io"), Marketing.OPT_IN, Plan.PREMIUM));
check(after.created.get(0).plan() == Plan.PREMIUM, "after: the plan is named");
try {
new Email("ana"); // a swapped value is caught where it is created
check(false, "should reject");
} catch (IllegalArgumentException expected) { }
System.out.println(after.created.get(0));
}
}
from dataclasses import dataclass
from enum import Enum
# ---------- before: connascence of position and meaning ----------
created_before: list[tuple] = []
def register_before(username: str, email: str, marketing: bool, plan: int) -> None:
# plan: 1 = free, 2 = premium, 3 = team
created_before.append((username, email, marketing, plan))
register_before("ana@x.io", "ana", True, 3) # swapped, wrong code, no error
assert created_before[0][0] == "ana@x.io"
# ---------- after: connascence of name and type ----------
class Plan(Enum):
FREE = "free"
PREMIUM = "premium"
TEAM = "team"
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self) -> None:
if "@" not in self.value:
raise ValueError(f"not an email: {self.value}")
@dataclass(frozen=True)
class Registration:
username: str
email: Email
plan: Plan
marketing: bool = False
created: list[Registration] = []
def register(*, username: str, email: Email, plan: Plan, marketing: bool = False) -> None:
created.append(Registration(username, email, plan, marketing))
register(username="ana", email=Email("ana@x.io"), plan=Plan.PREMIUM, marketing=True)
assert created[0].plan is Plan.PREMIUM
try:
register("ana", Email("ana@x.io"), Plan.TEAM) # type: ignore[misc] positional call rejected
raise AssertionError("positional call accepted")
except TypeError:
pass
try:
Email("ana")
raise AssertionError("bad email accepted")
except ValueError:
pass
print(created[0])
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: connascence of position and meaning ----------
const createdBefore: string[] = [];
// plan: 1 = free, 2 = premium, 3 = team
function registerBefore(username: string, email: string, marketing: boolean, plan: number): void {
createdBefore.push(`${username}|${email}|${marketing}|${plan}`);
}
registerBefore("ana@x.io", "ana", true, 3); // swapped, wrong code, compiles
check(createdBefore[0]!.startsWith("ana@x.io|ana"), "before: silent mistake");
// ---------- after: connascence of name and type ----------
type Plan = "free" | "premium" | "team";
type Email = string & { readonly __brand: "Email" };
function email(value: string): Email {
if (!value.includes("@")) throw new RangeError(`not an email: ${value}`);
return value as Email;
}
interface Registration {
username: string;
email: Email;
plan: Plan;
marketing?: boolean;
}
const created: Registration[] = [];
const register = (r: Registration): void => { created.push(r); };
register({ username: "ana", email: email("ana@x.io"), plan: "premium", marketing: true });
check(created[0]!.plan === "premium", "after: named fields");
// register({ username: "ana", email: "ana@x.io", plan: "gold" }) -> two compile errors
let rejected = false;
try { email("ana"); } catch { rejected = true; }
check(rejected, "after: bad email rejected at creation");
console.log(created[0]);
The "before" call compiles and runs in all three languages with the username and email swapped. In the "after" versions, the same mistake either doesn't compile (Java's types, TypeScript's branded Email) or fails at the call (Python's keyword-only parameters and the Email check). The code agrees on names and types rather than positions and magic numbers.
4.2 Dynamic connascence
The dynamic kinds are harder because no compiler sees them.
- Execution order. If
connect()must precedesend(), either make the constructor connect, or return aConnectionfromconnect()that is the only thing with asend()method. The type system then enforces the order. This is a common use of the Builder and of state-specific types. - Value. If
areamust always equalwidth × height, don't storeareaat all: compute it. Or make the object immutable so the values are set together once. See Immutability & Value Objects. - Identity. If two components must share one instance, pass that instance to both explicitly through constructors, rather than having each look it up from a global. See Designing for Testability.
- Timing. Timeouts that must be ordered (client timeout greater than server timeout, retry backoff shorter than lease expiry) belong next to each other in one configuration object, with a check that enforces the ordering at startup.
5. The Law of Demeter
The Law of Demeter was formulated at Northeastern University in 1987 by Ian Holland, working on the Demeter project (named after the Greek goddess of agriculture, because the project was about "growing" software). It's often summarised as "only talk to your immediate friends" or "don't talk to strangers."
Formally, a method m of an object O should only call methods on:
Oitself;m's parameters;- objects that
mcreates; O's own fields (its direct components).
What it rules out is calling methods on objects returned by other calls, that is, reaching through one object to get at another.
flowchart LR
M["Cashier.charge(customer)"] -->|"OK: parameter"| C["customer.pay(amount)"]
M -->|"OK: own field"| T["till.record(amount)"]
M -->|"OK: created here"| R["new Receipt(...)"]
M -.->|"Not OK: a stranger"| W["customer.getWallet().take(amount)"]
5.1 Train wrecks
The visible symptom is a train wreck: a chain of calls like order.getCustomer().getAddress().getCity(), each car coupled to the next. The calling code now depends on four classes and on the structure connecting them. If customers start having several addresses, every train wreck that walks that path breaks.
David Bock's essay The Paperboy, the Wallet, and the Law of Demeter made the point with a story. Here's the same idea in a café. The cashier reaches into the customer's pocket, pulls out the wallet, counts the money and takes some. In real life you'd never let a cashier do that. You'd hand over the amount, and you would decide whether to pay with cash, a card or a gift voucher.
// ---------- before: the cashier reaches through the customer into the wallet ----------
final class WalletBefore {
private long cents;
WalletBefore(long cents) { this.cents = cents; }
long getCents() { return cents; }
void setCents(long c) { cents = c; }
}
final class CustomerBefore {
private final WalletBefore wallet;
CustomerBefore(WalletBefore wallet) { this.wallet = wallet; }
WalletBefore getWallet() { return wallet; }
}
final class CashierBefore {
long takings;
void charge(CustomerBefore customer, long price) {
WalletBefore w = customer.getWallet(); // a stranger
if (w.getCents() < price) throw new IllegalStateException("insufficient funds");
w.setCents(w.getCents() - price);
takings += price;
}
}
// ---------- after: tell the customer to pay; how is their business ----------
final class Customer {
private long walletCents;
private long voucherCents;
Customer(long walletCents, long voucherCents) { this.walletCents = walletCents; this.voucherCents = voucherCents; }
/** Pays the amount, vouchers first. Returns false and changes nothing if it can't be covered. */
boolean pay(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
if (walletCents + voucherCents < cents) return false;
long fromVoucher = Math.min(voucherCents, cents);
voucherCents -= fromVoucher;
walletCents -= cents - fromVoucher;
return true;
}
long walletCents() { return walletCents; }
}
final class Cashier {
private long takings;
void charge(Customer customer, long price) {
if (!customer.pay(price)) throw new IllegalStateException("payment declined");
takings += price;
}
long takings() { return takings; }
}
class DemeterDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
CashierBefore oldCashier = new CashierBefore();
oldCashier.charge(new CustomerBefore(new WalletBefore(1_000)), 300);
check(oldCashier.takings == 300, "before works, but the cashier knows about wallets");
Customer ana = new Customer(1_000, 200); // vouchers were added: Cashier did not change
Cashier cashier = new Cashier();
cashier.charge(ana, 300);
check(cashier.takings() == 300 && ana.walletCents() == 900, "voucher used first");
try { cashier.charge(ana, 5_000); check(false, "should decline"); }
catch (IllegalStateException expected) { }
check(ana.walletCents() == 900 && cashier.takings() == 300, "nothing changed on decline");
System.out.println("the cashier only talks to the customer");
}
}
# ---------- before: the cashier reaches through the customer into the wallet ----------
class WalletBefore:
def __init__(self, cents: int) -> None:
self.cents = cents
class CustomerBefore:
def __init__(self, wallet: WalletBefore) -> None:
self.wallet = wallet
class CashierBefore:
def __init__(self) -> None:
self.takings = 0
def charge(self, customer: CustomerBefore, price: int) -> None:
if customer.wallet.cents < price: # a stranger
raise RuntimeError("insufficient funds")
customer.wallet.cents -= price
self.takings += price
# ---------- after: tell the customer to pay; how is their business ----------
class Customer:
def __init__(self, wallet_cents: int, voucher_cents: int = 0) -> None:
self._wallet = wallet_cents
self._voucher = voucher_cents
def pay(self, cents: int) -> bool:
"""Pays vouchers first. Returns False and changes nothing if it can't be covered."""
if cents <= 0:
raise ValueError("amount must be positive")
if self._wallet + self._voucher < cents:
return False
from_voucher = min(self._voucher, cents)
self._voucher -= from_voucher
self._wallet -= cents - from_voucher
return True
@property
def wallet_cents(self) -> int:
return self._wallet
class Cashier:
def __init__(self) -> None:
self.takings = 0
def charge(self, customer: Customer, price: int) -> None:
if not customer.pay(price):
raise RuntimeError("payment declined")
self.takings += price
old = CashierBefore()
old.charge(CustomerBefore(WalletBefore(1_000)), 300)
assert old.takings == 300
ana, cashier = Customer(1_000, 200), Cashier()
cashier.charge(ana, 300)
assert cashier.takings == 300 and ana.wallet_cents == 900
try:
cashier.charge(ana, 5_000)
raise AssertionError("should decline")
except RuntimeError:
pass
assert ana.wallet_cents == 900 and cashier.takings == 300
print("the cashier only talks to the customer")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
// ---------- before: the cashier reaches through the customer into the wallet ----------
class WalletBefore { constructor(public cents: number) {} }
class CustomerBefore { constructor(public wallet: WalletBefore) {} }
class CashierBefore {
takings = 0;
charge(customer: CustomerBefore, price: number): void {
if (customer.wallet.cents < price) throw new Error("insufficient funds"); // a stranger
customer.wallet.cents -= price;
this.takings += price;
}
}
// ---------- after: tell the customer to pay; how is their business ----------
class Customer {
constructor(private walletCents: number, private voucherCents = 0) {}
/** Pays vouchers first. Returns false and changes nothing if it can't be covered. */
pay(cents: number): boolean {
if (cents <= 0) throw new RangeError("amount must be positive");
if (this.walletCents + this.voucherCents < cents) return false;
const fromVoucher = Math.min(this.voucherCents, cents);
this.voucherCents -= fromVoucher;
this.walletCents -= cents - fromVoucher;
return true;
}
get wallet(): number { return this.walletCents; }
}
class Cashier {
private earned = 0;
charge(customer: Customer, price: number): void {
if (!customer.pay(price)) throw new Error("payment declined");
this.earned += price;
}
get takings(): number { return this.earned; }
}
const old = new CashierBefore();
old.charge(new CustomerBefore(new WalletBefore(1_000)), 300);
check(old.takings === 300, "before works");
const ana = new Customer(1_000, 200);
const cashier = new Cashier();
cashier.charge(ana, 300);
check(cashier.takings === 300 && ana.wallet === 900, "voucher first");
let declined = false;
try { cashier.charge(ana, 5_000); } catch { declined = true; }
check(declined && ana.wallet === 900 && cashier.takings === 300, "nothing changed on decline");
console.log("the cashier only talks to the customer");
When vouchers were added, the "after" Cashier didn't change, because it never knew how customers pay. The "before" cashier would have needed rewriting, along with every other class that reaches into wallets.
5.2 What the law doesn't forbid
The Law of Demeter is often applied as "count the dots", which is wrong. It's about reaching through objects to their collaborators, not about syntax.
- Fluent interfaces and builders.
builder.name("x").age(3).build()calls methods on the same object (or a builder designed to be chained). No strangers are involved. - Value transformations.
text.trim().toLowerCase().split(",")andstream.filter(…).map(…)each return a new value of a type you already depend on. You're not navigating someone's internals. - Data structures. A DTO or record that exists to expose data (
response.body().items()) isn't hiding anything. Robert C. Martin's Clean Code draws this line: the law applies to objects that hide data behind behaviour, not to plain data structures. - Navigating within your own aggregate. An
Orderreading its ownlines.get(i).price()is talking to its own components.
The question to ask isn't "how many dots?" but "does this code depend on the internal structure of something it doesn't own?"
5.3 Fixing train wrecks without wrapper explosion
The naive fix for order.getCustomer().getAddress().getCity() is to add order.getCustomerCity(). Do that for every path, and Order grows dozens of forwarding methods that have nothing to do with orders. That's the Law of Demeter going too far.
Better fixes, roughly in order of preference:
- Ask why the caller needs it, and move the behaviour. If the caller wants the city to compute shipping, maybe
order.shippingZone()orcustomer.shippingAddress()handing anAddressto aShippingCalculatoris the real operation. - Pass what's needed as a parameter. If a method needs a city, give it a city or an
Address, not anOrder(stamp → data coupling, again). - Accept it for data. If
Addressis an immutable value object and the code is rendering an invoice,order.customer().address().city()on records is fine.
6. Tell, don't ask
Tell, don't ask is the behavioural cousin of the Law of Demeter. It was popularised by Andy Hunt and Dave Thomas (the Pragmatic Programmers) in an early-2000s article. The idea: rather than asking an object for its data and making a decision on its behalf, tell it what you want and let it decide. The decision belongs with the data.
Ask-style code is usually a sign of an anaemic model. The rule about when an order can ship lives in a warehouse service. Then a support tool needs to ship orders too, and someone writes the status change directly, skipping the rule.
import java.util.*;
enum Status { NEW, PAID, SHIPPED }
record Item(String sku, boolean inStock) {}
// ---------- before: ask for the data, decide elsewhere ----------
final class OrderBefore {
private Status status = Status.NEW;
private final List<Item> items;
OrderBefore(List<Item> items) { this.items = items; }
Status getStatus() { return status; }
void setStatus(Status s) { status = s; }
List<Item> getItems() { return items; }
}
final class Warehouse {
void dispatch(OrderBefore o) {
if (o.getStatus() == Status.PAID && o.getItems().stream().allMatch(Item::inStock)) o.setStatus(Status.SHIPPED);
}
}
final class SupportTool {
void forceShip(OrderBefore o) { o.setStatus(Status.SHIPPED); } // the rule was never here
}
// ---------- after: tell the order what to do; it owns the rule ----------
final class Order {
private Status status = Status.NEW;
private final List<Item> items;
Order(List<Item> items) {
if (items.isEmpty()) throw new IllegalArgumentException("an order needs items");
this.items = List.copyOf(items);
}
void pay() {
if (status != Status.NEW) throw new IllegalStateException("already " + status);
status = Status.PAID;
}
void ship() {
if (status != Status.PAID) throw new IllegalStateException("cannot ship a " + status + " order");
if (!items.stream().allMatch(Item::inStock)) throw new IllegalStateException("items out of stock");
status = Status.SHIPPED;
}
Status status() { return status; }
}
class TellDontAskDemo {
static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }
public static void main(String[] args) {
OrderBefore unpaid = new OrderBefore(List.of(new Item("tea", true)));
new SupportTool().forceShip(unpaid);
check(unpaid.getStatus() == Status.SHIPPED, "before: an unpaid order shipped");
Order order = new Order(List.of(new Item("tea", true)));
try { order.ship(); check(false, "should refuse"); } catch (IllegalStateException expected) { }
order.pay();
order.ship();
check(order.status() == Status.SHIPPED, "after: shipped through the rule");
System.out.println("the rule lives with the data");
}
}
from dataclasses import dataclass
from enum import Enum, auto
class Status(Enum):
NEW = auto()
PAID = auto()
SHIPPED = auto()
@dataclass(frozen=True)
class Item:
sku: str
in_stock: bool
# ---------- before: ask for the data, decide elsewhere ----------
class OrderBefore:
def __init__(self, items: list[Item]) -> None:
self.status = Status.NEW
self.items = items
def dispatch(o: OrderBefore) -> None:
if o.status is Status.PAID and all(i.in_stock for i in o.items):
o.status = Status.SHIPPED
def force_ship(o: OrderBefore) -> None:
o.status = Status.SHIPPED # the rule was never here
# ---------- after: tell the order what to do; it owns the rule ----------
class Order:
def __init__(self, items: list[Item]) -> None:
if not items:
raise ValueError("an order needs items")
self._items = tuple(items)
self._status = Status.NEW
def pay(self) -> None:
if self._status is not Status.NEW:
raise RuntimeError(f"already {self._status.name}")
self._status = Status.PAID
def ship(self) -> None:
if self._status is not Status.PAID:
raise RuntimeError(f"cannot ship a {self._status.name} order")
if not all(i.in_stock for i in self._items):
raise RuntimeError("items out of stock")
self._status = Status.SHIPPED
@property
def status(self) -> Status:
return self._status
unpaid = OrderBefore([Item("tea", True)])
force_ship(unpaid)
assert unpaid.status is Status.SHIPPED # an unpaid order shipped
order = Order([Item("tea", True)])
try:
order.ship()
raise AssertionError("should refuse")
except RuntimeError:
pass
order.pay()
order.ship()
assert order.status is Status.SHIPPED
print("the rule lives with the data")
function check(ok: boolean, what: string): void {
if (!ok) throw new Error(what);
}
type Status = "NEW" | "PAID" | "SHIPPED";
interface Item { readonly sku: string; readonly inStock: boolean }
// ---------- before: ask for the data, decide elsewhere ----------
class OrderBefore {
status: Status = "NEW";
constructor(public items: Item[]) {}
}
const dispatch = (o: OrderBefore): void => {
if (o.status === "PAID" && o.items.every((i) => i.inStock)) o.status = "SHIPPED";
};
const forceShip = (o: OrderBefore): void => { o.status = "SHIPPED"; }; // the rule was never here
// ---------- after: tell the order what to do; it owns the rule ----------
class Order {
#status: Status = "NEW";
readonly #items: readonly Item[];
constructor(items: Item[]) {
if (items.length === 0) throw new RangeError("an order needs items");
this.#items = [...items];
}
pay(): void {
if (this.#status !== "NEW") throw new Error(`already ${this.#status}`);
this.#status = "PAID";
}
ship(): void {
if (this.#status !== "PAID") throw new Error(`cannot ship a ${this.#status} order`);
if (!this.#items.every((i) => i.inStock)) throw new Error("items out of stock");
this.#status = "SHIPPED";
}
get status(): Status { return this.#status; }
}
const unpaid = new OrderBefore([{ sku: "tea", inStock: true }]);
forceShip(unpaid);
check(unpaid.status === "SHIPPED", "before: an unpaid order shipped");
dispatch(unpaid);
const order = new Order([{ sku: "tea", inStock: true }]);
let refused = false;
try { order.ship(); } catch { refused = true; }
check(refused, "after: refuses unpaid");
order.pay();
order.ship();
check(order.status === "SHIPPED", "after: shipped through the rule");
console.log("the rule lives with the data");
After the change there's only one way to ship an order, and it checks the rule. The support tool can't skip it, because there's no setter. Tell-don't-ask also reduces coupling: callers depend on ship(), not on status, items and the rule connecting them.
6.1 Where tell-don't-ask stops
Martin Fowler's note on the principle adds a caveat worth repeating: he doesn't use it as a strict rule, and neither should you. Getters are fine when:
- You're displaying or reporting. A UI showing an order's status must ask for it. Moving rendering into
Orderwould couple the domain to presentation. - The decision genuinely belongs to the caller. A pricing service deciding a discount based on a customer's loyalty tier is asking for a fact about the customer, but the discount policy belongs to pricing, not to the customer.
- You're working with values.
money.amount()for formatting is fine.
The principle works best alongside command-query separation: commands (ship(), pay()) tell objects to change themselves and enforce their rules, while queries (status()) report facts without side effects. Ask-style code goes wrong when it's used to change state from outside, not when it reads.
7. Reviewing a design in five minutes
In an interview, you usually have a few minutes between drawing the class diagram and starting to code. That's the moment to run a quick cohesion and coupling review, out loud. Here's a routine that fits in that window, applied to a typical first-draft elevator design with ElevatorSystem, Elevator, Request, Floor and Display.
- Read each class name and say its job in one sentence. "
Elevatormoves one car and holds its stops.ElevatorSystem… accepts requests, picks an elevator, updates displays, logs trips and computes energy use." The second sentence has several "and"s, so it's a cohesion problem. Picking an elevator is a scheduling policy that interviewers love to vary, so it becomes aSchedulerinterface. - Follow each arrow and ask what crosses it. If
Displayreadselevator.currentFloorandelevator.directionandelevator.doorsOpen, it's coupled to three fields. Could the elevator publish oneElevatorStatusvalue instead? That's one stable type crossing the boundary rather than three fields. - Look for chains.
system.getElevators().get(i).getStops().add(floor)reaches through the system and the elevator into a collection. Replace it withelevator.addStop(floor), which is called by whatever owns the decision. - Look for flags and codes.
Request(int floor, int dir)withdiras 1 or -1, ormove(boolean up), are connascence of meaning and control coupling. ADirectionenum fixes both. - Look for shared mutable state. Do two classes both write to the same list of pending requests? Then exactly one of them should own it, and the other should call a method on the owner. This also marks where concurrency control will be needed later.
- Check the dependency direction. Domain classes (
Elevator,Request) shouldn't depend on infrastructure (Display, a logger, a hardware driver). If they need to notify something, they depend on an interface that the infrastructure implements.
You won't fix all of these in the interview, and you shouldn't try. Naming two or three and fixing the one the interviewer cares about shows the habit. It also tends to set up the extension questions nicely: once scheduling is behind an interface, "add a peak-hour scheduling mode" is a new class.
8. When these ideas go too far
| Over-applied | What it looks like | Better |
|---|---|---|
| Cohesion as "one method per class" | OrderValidator, OrderTotaller, OrderStatusChanger that all need Order's internals | Keep a concept's data and rules together. Split by reason to change, not by verb |
| Decoupling everything | Interfaces for every class, events instead of direct calls, a mediator for two objects | Coupling to stable things is fine. Direct calls are easier to follow than events. Decouple across volatile boundaries |
| Event-driven to avoid coupling | Publishers and subscribers that are still logically coupled, just invisibly | The coupling still exists in what the events mean. Use events when there are many independent listeners, not to hide a single dependency |
| Law of Demeter as dot-counting | order.getCustomerAddressCity(), order.getCustomerAddressPostcode(), and twenty more | Move behaviour, pass parameters, or accept navigation over value objects |
| Tell-don't-ask for everything | Order.renderAsHtml(), Order.saveToDatabase() | Domain objects own domain rules, not presentation or persistence |
| Fear of all connascence | Avoiding positional arguments for a two-argument Point(x, y) | Weak, local connascence is fine. Worry about strong, distant, high-degree connascence |
The overall rule: coupling isn't bad, unmanaged coupling is. Depend on stable abstractions, keep strong dependencies local, and make the rest visible.
9. How it shows up in LLD interviews
You'll rarely be asked "define cohesion." You'll be judged on it through your class diagram and code.
Signals interviewers look for:
- Classes named after one concept (
SeatMap,FareCalculator,Ticket) rather than after the system (MovieManager) or a vague role (Helper). - Small, purposeful interfaces between components.
ParkingLotdepends on aSpotAllocatorwithallocate(vehicle)rather than on its internal maps. - No train wrecks in core flows.
elevator.getController().getQueue().add(request)is a red flag.controller.submit(request)isn't. - Rules on the object that owns the data.
booking.cancel(now)enforcing the cancellation window, rather than a service that reads three fields and writes one. - Explicit dependencies. Collaborators passed into constructors, not looked up from statics.
Phrases that show the vocabulary:
- "I'm keeping fare calculation out of
Ticketbecause it changes for different reasons: pricing rules versus ticket lifecycle." - "The allocator only needs the vehicle size, so I'll pass that, not the whole vehicle."
- "Instead of the controller reaching into the elevator's queue, I'll tell the elevator to accept a request and let it decide where it goes."
- "This flag parameter is control coupling. I'll replace it with two methods or a strategy."
- "That's connascence of meaning, the magic status codes, so I'll use an enum."
Common follow-ups:
- "Your
BookingServicedepends on six things. Is that a problem?" Look at whether it's a coordinator (fine, it's communicational or sequential cohesion) or implementing six concerns (split it). - "Isn't
order.getItems().size()a Law of Demeter violation?" Pragmatically no, ifitems()returns an unmodifiable collection or a value. A dedicatedorder.itemCount()is nicer if callers need it often. - "How would you decouple the notification sending from booking?" An interface (
Notifier) injected into the service, or an event if several independent reactions are expected.
10. Interview questions
-
"What's the difference between cohesion and coupling?" Cohesion is how well the parts inside a unit belong together. Coupling is how much units depend on each other. You want high cohesion and low coupling, and improving cohesion usually reduces coupling, because a concept that lives in one place doesn't need others to know about it.
-
"How do you tell if a class has low cohesion?" Map which methods use which fields. If they split into groups that share nothing, you have several classes in one. Other signs are vague names (
Manager,Utils) and tests that need unrelated setup. -
"Name some kinds of coupling and how to reduce each." Content coupling (reaching into internals) is fixed with encapsulation. Common coupling (global mutable state) is fixed by passing values or injecting objects. Control coupling (flag parameters) is fixed with separate methods or polymorphism. Stamp coupling (passing a whole object for one field) is fixed by passing the field.
-
"What is connascence and why is it useful?" Two pieces of code are connascent if changing one requires changing the other. It gives coupling a vocabulary: name, type, meaning, position and algorithm (static), plus execution, timing, value and identity (dynamic). The rule is to weaken strong connascence and keep strong connascence local.
-
"State the Law of Demeter." A method should only call methods on its own object, its parameters, objects it creates, and its object's direct fields, not on objects returned by other calls. It prevents code from depending on the internal structure of objects it doesn't own.
-
"Is
list.stream().filter(...).map(...).toList()a Law of Demeter violation?" No. Each call returns a value in a type you already depend on, and you're not navigating someone else's internals. The law is about reaching through collaborators, not counting dots. Builders and fluent APIs are fine for the same reason. -
"How do you fix
order.getCustomer().getAddress().getCity()?" Ask why the caller needs the city. Usually there's a behaviour to move (order.shippingZone()) or a parameter to pass (give the method anAddress). Adding forwarding getters for every path just moves the problem. For immutable value objects used in rendering, navigation is acceptable. -
"What is tell-don't-ask? Are getters bad?" Tell objects what to do instead of pulling their data out and deciding for them, so rules live with the data they guard. Getters aren't bad. Use them for display, reporting and facts other objects legitimately use. The problem is setting state from outside based on what you asked.
-
"Your service class depends on six other classes. Is it too coupled?" It depends on what kind of dependence. A coordinator that calls six focused collaborators through interfaces is fine. A class implementing six concerns itself, or depending on concrete classes' internals, isn't. Also check whether some dependencies always appear together, which suggests a missing abstraction.
-
"How do events affect coupling?" They remove compile-time coupling between publisher and subscriber, but the logical coupling remains in the meaning of the event. They're worth it when several independent reactions exist. For one consumer, a direct call through an interface is easier to follow and debug.