Building Software
Sections

Contents Section 6, Design

Managing Complexity

Coupling, cohesion, information hiding and simplicity: the principles that decide whether a codebase gets easier or harder to change over time.

Section 6 of 9, subsection 1 of 6. Depth: do. A 9-minute read.

Mistakes to catch in review

  1. A factory, an interface and a configuration loader added for a feature that has exactly one implementation.

  2. The same tax-rounding rule copied into three files, so a later fix lands in only one of them.

  3. A catch-all utilities module that everything imports, coupling unrelated parts of the system.

  4. A helper named processData that validates and saves in one call, so a caller that only wanted validation writes to the database.

The price of the next change

An agent adds gift wrapping to your checkout. The feature is small: each wrapped item costs $3.50. The diff that comes back has a GiftWrapPricingProvider interface, a StandardGiftWrapPricing class that implements it, a GiftWrapPricingFactory that builds the class, and a loader that reads the $3.50 from a JSON config file. The tests pass and the feature works.

In the same diff, the agent needed the free-shipping rule to show a shipping line in the order confirmation email, so it wrote the rule again in the email module. Checkout and invoicing already had their own copies, so there are now three.

Nothing here is a bug today. The problem shows up in six months, when someone changes the shipping threshold and one copy doesn't get the update, or when someone has to read four files to find out what gift wrapping costs.

What complexity is

John Ousterhout, in A Philosophy of Software Design, defines complexity as whatever makes a program hard to understand or hard to change. The definition is useful because you can test it. Pick a likely change, such as "free shipping now starts at $75", and count how many places you would have to find, read and edit to make it safely. The more places, and the harder they are to find, the more complex the code is with respect to that change.

Tree diagram. A box labelled Complexity, hard to understand or change, branches into two boxes: Essential, which no design removes, and Accidental, what we add, which is highlighted. Accidental forks two ways: an arrow labelled remove it leads to a pill labelled Removed, and an arrow labelled kept leads to Technical debt, which charges interest.
Only the accidental branch can be removed. When it stays in the code it becomes technical debt, and every later change pays a little interest on it.

Fred Brooks split this difficulty in two. Essential complexity comes from the problem itself: tax law has cases, shipping has zones, refunds have deadlines, and no design makes those rules go away. Accidental complexity is what we add while solving the problem: layers nobody needed, rules written twice, names that hide what a function does.

You can only remove the accidental kind. Technical debt is accidental complexity that stays in the code, either kept on purpose to ship sooner or discovered later. Like financial debt, it charges interest: every later change that touches that code costs a little more, and the cost repeats on every change until someone pays down the principal.

Taking on debt on purpose can be the right call. The trouble with agent-written code is debt you take on without noticing, because the agent adds it without mentioning it.

Coupling and cohesion

Two parts of a program are coupled when a change to one forces a change to the other. Some coupling is unavoidable, because code that cooperates has to agree on something. The goal is to make each agreement explicit and to keep it in one place.

Cohesion is the other side. A module is cohesive when the things inside it change for the same reason. A shipping module that holds the threshold, the flat fee and the function that combines them is cohesive: when shipping policy changes, you open one file. A module that holds date formatting, money rounding and a database connection has low cohesion, because those three things change for unrelated reasons and share a file only by accident.

David Parnas made the underlying argument in 1972. Build each module around a design decision that is likely to change, and hide that decision inside the module, so that code elsewhere depends only on what the module promises. The free-shipping threshold is exactly that kind of decision. The rest of the program should be able to ask "what does shipping cost for this subtotal?" without knowing the threshold exists.

A rule written three times

Here are the three copies of the shipping rule, as they might look after a few months of agent-assisted work.

TypeScript
// checkout.ts
export function shippingFee(subtotalCents: number): number {
  return subtotalCents >= 5000 ? 0 : 599;
}

// invoice.ts
function shippingLine(subtotalCents: number): number {
  if (subtotalCents >= 5000) return 0;
  return 599;
}

// order-email.ts
const shippingCents = order.subtotalCents > 5000 ? 0 : 599;

Read the third line closely. It uses > where the other two use >=. A customer whose cart is exactly $50.00 sees free shipping at checkout, sees free shipping on the invoice, and gets an email saying they paid $5.99. The copies already disagree, and no test caught it because each copy has its own tests, or none.

Now the business raises the threshold to $75. Someone searches for 5000, finds checkout.ts, and changes it. The invoice still says shipping is free on a $60 order, while checkout charged $5.99. Duplicated rules drift this way because the second and third copies depend on someone remembering they exist.

Before and after. On the left, under Three copies, a pill labelled Raise threshold, to $75, has a solid arrow to checkout.ts, changed to $75, labelled search 5000, and dashed arrows to invoice.ts, still 5000, and order-email.ts, still greater than 5000. A note reads: copies drift apart. On the right, under One rule, checkout.ts, invoice.ts and order-email.ts each point to a highlighted shipping.ts holding shippingFeeCents. A note reads: one change, one place.
Searching for 5000 finds the checkout copy, so the invoice and the email keep the old rule. With one shipping module, every caller picks up the change from a single edit.

The fix is to move the rule to one place and have every caller use it.

TypeScript
// shipping.ts
export const FREE_SHIPPING_THRESHOLD_CENTS = 5000;
export const FLAT_SHIPPING_CENTS = 599;

export function shippingFeeCents(subtotalCents: number): number {
  return subtotalCents >= FREE_SHIPPING_THRESHOLD_CENTS ? 0 : FLAT_SHIPPING_CENTS;
}

A refactor is a change to structure that leaves behavior alone. Tests that pass before and after are evidence that the behavior they cover stayed the same, and they say nothing about what they do not cover. Write the test first, against the current code, at the values where the rule could flip: just under the threshold, exactly on it, and just over it.

TypeScript
import { test, expect } from "bun:test";
import { shippingFeeCents } from "./shipping";

const cases: Array<[number, number]> = [
  [0, 599],
  [4999, 599],
  [5000, 0],
  [5001, 0],
];

for (const [subtotal, fee] of cases) {
  test(`subtotal ${subtotal} cents ships for ${fee} cents`, () => {
    expect(shippingFeeCents(subtotal)).toBe(fee);
  });
}

Run the same four cases against each old copy before you delete it.

TypeScriptRuns in your browser
// The three copies, as they are today.
const checkout = (subtotalCents: number) => (subtotalCents >= 5000 ? 0 : 599);
const invoice = (subtotalCents: number) => {
  if (subtotalCents >= 5000) return 0;
  return 599;
};
const orderEmail = (subtotalCents: number) => (subtotalCents > 5000 ? 0 : 599);

const cases: Array<[number, number]> = [
  [0, 599],
  [4999, 599],
  [5000, 0],
  [5001, 0],
];

for (const [name, fee] of Object.entries({ checkout, invoice, orderEmail })) {
  const wrong = cases
    .filter(([subtotal, expected]) => fee(subtotal) !== expected)
    .map(([subtotal, expected]) => `${subtotal} gives ${fee(subtotal)}, expected ${expected}`);
  console.log(name.padEnd(10), wrong.length === 0 ? "passes" : `fails: ${wrong.join("; ")}`);
}

The checkout and invoice copies pass. The email copy fails at 5000, where it returns 599. That failure is the useful result: merging the copies changes what the email says for a $50.00 order, so this is a behavior change, however small, and a person has to decide which answer is correct.

Make that decision in its own commit, then do the pure structural move in another. When a single diff mixes "moved code" with "changed what the code does", a reviewer can't tell which lines are which.

When two copies should stay two copies

Merging duplicates is right when the copies express the same rule. It is wrong when they only look alike.

Suppose the loyalty program gives members a bonus when they spend $50 in a month. That code might read if (monthlySpendCents >= 5000), identical in shape to the shipping rule. An agent looking for duplication will happily extract isOverFiftyDollars() and point both callers at it.

Now shipping policy and loyalty policy share a function, and the day marketing moves the loyalty bonus to $40, someone either changes shipping by accident or adds a parameter to the shared helper. After a few rounds of that, the helper has flags for every caller and nobody can say what it does.

Sandi Metz put the trade-off in one line: "duplication is far cheaper than the wrong abstraction." The question that separates the two cases is whether the copies can change independently. Ownership is a clue, so ask who decides the value. If the same person, following the same policy, would always change both copies together, they are one rule and belong in one place. If two different people own them, they are two rules that happen to share a number, and they should stay apart.

Layers for a feature that has one case

Back to gift wrapping. Here is roughly what the agent wrote.

TypeScript
interface GiftWrapPricingProvider {
  priceCents(itemCount: number): number;
}

class StandardGiftWrapPricing implements GiftWrapPricingProvider {
  constructor(private readonly perItemCents: number) {}
  priceCents(itemCount: number): number {
    return itemCount * this.perItemCents;
  }
}

class GiftWrapPricingFactory {
  static create(config: { perItemCents: number }): GiftWrapPricingProvider {
    return new StandardGiftWrapPricing(config.perItemCents);
  }
}

// elsewhere: GiftWrapPricingFactory.create(loadConfig("gift-wrap.json"))

Each piece exists so that some future second implementation could be swapped in. There is no second implementation, and nobody has asked for one. The whole thing does one multiplication.

TypeScript
const GIFT_WRAP_PER_ITEM_CENTS = 350;

export function giftWrapCents(itemCount: number): number {
  return itemCount * GIFT_WRAP_PER_ITEM_CENTS;
}

Ousterhout calls the first version shallow: its interfaces are about as large as the work behind them, so each layer adds something to learn and hides almost nothing. A deep module is the opposite, a small interface over a lot of functionality. A reader of the shallow version has to open four files to learn that wrapping costs $3.50 per item.

Two designs side by side. On the left, under Shallow layers, three rows, each an Interface box beside a Work box of about the same size, with a note beneath: each layer adds something to learn. On the right, Deep module: a small Interface pill over a large, highlighted Work box, a lot of functionality.
A shallow module's interface is about as large as the work behind it, so each layer adds something to learn. A deep module hides a lot of work behind a small interface.

The principle behind the deletion is often called YAGNI, "you aren't gonna need it": build for the requirements you have, and add generality when a second real case shows up. When it does, you'll know what actually varies between the two cases, which is information you don't have when you guess in advance. Adding an interface to a one-function module later takes minutes.

Before deleting a layer, ask what it does that the simpler version would not. The config loader is the piece to check carefully.

If operations staff edit gift-wrap.json in production to change the price without a deploy, the loader is a real requirement and the constant would break their workflow. If the file is only ever changed through a code commit, the loader adds a file read and a failure mode and buys nothing. To find which is true, look at where the file is deployed, at its history, and at everything else that reads it, such as build scripts and other tools, before replacing it with a constant.

The module everything imports

Agents like to create utils.ts and add to it whenever a small function has no obvious home. After a while it holds formatDate, roundMoney, slugify, retryFetch and getDbConnection, and nearly every file in the project imports it.

That file now couples unrelated parts of the system. If getDbConnection opens a connection pool when the module loads, then a unit test for slugify needs database credentials to run.

A highlighted box, `utils.ts`, couples unrelated parts, sits in the middle. The `slugify` test, which needs database credentials, imports it, and `utils.ts` opens a Database cylinder whose pool opens at load. An edit to `retryFetch` points into `utils.ts`, and a live arrow carries that change on to the payment code, which is re-reviewed and re-tested.
Everything that imports utils.ts inherits whatever it does. The slugify test needs database credentials because of a pool opened at load, and an edit to retryFetch puts the payment code back under review.

A change to retryFetch shows up as a change to a file that the payment code imports, so the payment code has to be re-reviewed and re-tested for an edit it never cared about. The question that exposes a module like this is simple: what do the functions in it have in common, other than being small? If the honest answer is nothing, each function should move next to the code that uses it, and roundMoney probably belongs in a money module with the other money rules.

You can find the most tightly coupled module in a codebase with two measurements. The first is how many files depend on a module. This command counts the files that import utils; run it once for each candidate module and compare the counts:

Shell
grep -rlE "from ['\"].*/utils['\"]" src | wc -l

The second ranks files by how often they changed, since a module many files depend on is riskiest when it changes often. A stable one can still hurt through its load-time side effects, like the connection pool above:

Shell
git log --since="6 months ago" --name-only --format= -- src \
  | sort | uniq -c | sort -rn | head -20

A module with a high import count that also sits near the top of the change list is where changes spread. For that file, name the specific changes it makes hard: which edits force a re-test of unrelated features, and which teams have to coordinate before touching it.

Names that say everything the function does

The last tell is the name. Here is a helper an agent might write while building an order form.

TypeScript
async function processData(order: OrderInput): Promise<Order> {
  if (order.items.length === 0) throw new Error("order has no items");
  if (order.items.some((item) => item.qty <= 0)) throw new Error("bad quantity");
  return db.orders.insert(order);
}

Later, a different task asks for a "check my order" button that validates the cart before payment. The agent searches for existing validation, finds processData, sees that it throws on bad input, and calls it. Every click on "check my order" now inserts an order into the database. The name gave no hint that the function writes anything.

Split it into two functions whose names state their effects.

TypeScript
function validateOrder(order: OrderInput): void {
  if (order.items.length === 0) throw new Error("order has no items");
  if (order.items.some((item) => item.qty <= 0)) throw new Error("bad quantity");
}

async function saveOrder(order: OrderInput): Promise<Order> {
  validateOrder(order);
  return db.orders.insert(order);
}

The test for a name is whether a caller can predict every side effect from the name alone. Words like process, handle, manage and data fail that test because they fit any function. This matters more with agents in the loop, because an agent chooses which function to call largely by reading names, the same way the one that wrote "check my order" did.

The rule

For any diff, pick the next change you expect the business to ask for and count the places it would touch. If a single policy lives in more than one file, or a single file mixes policies that change for different reasons, or a layer exists for a case that doesn't exist yet, the diff made that count go up, and you can point to the exact lines that did it.

Check your understanding

6 questions on this lesson. Pick an answer to see whether it holds and why.

  1. 1An agent spots that these two constants are equal and proposes replacing both with one shared THIRTY_DAYS constant in a common module. What should you do?
    TypeScript
    // returns.ts
    const REFUND_WINDOW_DAYS = 30;
    
    // billing.ts
    const FREE_TRIAL_DAYS = 30;
    Show the answer

    Answer B. The two numbers match by coincidence. If finance moves refunds to 14 days, someone either changes trials by accident or has to split the constant again. One place to change helps only when the copies are one rule; sharing a constant is fine when it expresses a single policy.

  2. 2A one-line test for slugify fails in CI with "DATABASE_URL is not set". What causes it, and what is the fix?
    TypeScript
    // utils.ts
    export const pool = createPool(requireEnv("DATABASE_URL"));
    export function getDbConnection() { return pool.connect(); }
    export function slugify(title: string): string {
      return title.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-");
    }
    
    // slugify.test.ts
    import { slugify } from "./utils";
    test("slugify", () => expect(slugify("Hello World")).toBe("hello-world"));
    Show the answer

    Answer C. slugify never touches the database. The import runs every top-level line of utils.ts, and createPool needs the variable. Setting DATABASE_URL in CI makes the error go away but keeps the coupling: a pure text helper still cannot load without database credentials, and every file that imports utils.ts pays the same cost.

  3. 3An agent uses this function in a nightly report that reads settings for 50,000 users, most of whom have never opened their settings page. What does the report do to the database?
    TypeScript
    async function getUserSettings(userId: string): Promise<Settings> {
      const row = await db.settings.find(userId);
      if (row) return row;
      const defaults = defaultSettings();
      await db.settings.insert(userId, defaults);
      return defaults;
    }
    Show the answer

    Answer D. The function writes default rows whenever it finds none, and its name gives no hint of that, so a caller that only wanted to read ends up writing. Renaming it getOrCreateUserSettings, or splitting it into a pure read and a separate create, lets a caller predict the side effect from the name.

  4. 4You are about to replace three copies of a late-fee calculation with one shared function. Which step tells you whether the merge changes behavior?
    Show the answer

    Answer A. Tests written against the old copies show what each one does today, so a copy that fails them is one whose behavior the merge would change. Tests written after the merge pass by construction: they describe the new function and cannot reveal that one of the old copies used to answer differently at a boundary.

  5. 5None of these modules opens connections or does other work when it is imported. Which one most likely makes changes spread through the codebase?
    Output
    module          files that import it   commits in the last 6 months
    format.ts       84                     2
    config.ts       90                     1
    pricing.ts      61                     47
    report-job.ts   1                      58
    Show the answer

    Answer C. pricing.ts is both widely imported and frequently changed, so each of its 47 changes can reach 61 files. config.ts has the most importers, but it almost never changes and does nothing on load, so its reach rarely costs anything. report-job.ts changes often but nothing depends on it.

  6. 6An agent's diff moves the late-fee rule from three files into fees.ts. In the same diff it shortens the grace period from 14 days to 10, because one of the copies already used 10. All tests pass. What should the reviewer ask for?
    Show the answer

    Answer B. Two of the three copies used 14 days, so this diff changes what most customers are charged, and someone who owns the policy has to decide it. Passing tests only show that the behavior they cover still holds, and none of them checked a payment made on day 12. Separating the commits lets a reviewer see the move changed nothing and judge the policy change on its own.

You understand it when you can

Drill

An agent implemented a discount feature by adding a DiscountStrategyFactory, a DiscountProvider interface and a config loader, each with a single implementation, and copied the tax-rounding rule into two new files. Find what can be deleted without changing behavior, and where the copied rule will eventually disagree with the original.

Topics

Essential and Accidental Complexity
Separating the difficulty that comes from the problem from the difficulty added while solving it, and technical debt as the accidental complexity that was kept on purpose, with the interest it charges on every later change.
Coupling and Cohesion
Keeping related things together and unrelated things apart, so changes stay local.
Information Hiding and Deep Modules
Small interfaces over substantial functionality, so callers never depend on internal decisions.
Naming
Names that say what something does, which make code checkable by reading and easier for models to use correctly.
Simplicity and YAGNI
Building for the requirements you have, and adding generality only when a second real case appears.
Refactoring Under Tests
Changing structure in small steps without changing behavior, with tests proving each step.

Further reading

Start here

Short reads

Watch

Books

  • A Philosophy of Software Design. John Ousterhout, 2021, 2nd edition.

    Short chapters on deep versus shallow modules, information leakage, pulling complexity downward and choosing names give a reviewer a vocabulary for spotting over-layered agent code.

  • Refactoring: Improving the Design of Existing Code. Martin Fowler, 2018, 2nd edition.

    The catalog of behavior-preserving transformations (Extract Function, Inline Class, Remove Middle Man) and the discipline of running tests after each step are exactly what deleting a one-implementation factory safely requires.

  • Tidy First?: A Personal Exercise in Empirical Software Design. Kent Beck, 2023.

    A short book that treats coupling and cohesion as economic decisions and explains when to tidy structure before, after, or never relative to a behavior change.

Primary sources