APOSD Reading Notes 02: The Nature of Complexity

Notes on Chapter 2 of the second edition of A Philosophy of Software Design: a practical definition of complexity, its three symptoms—change amplification, cognitive load, and unknown unknowns—its two causes, dependency and obscurity, and why complexity accumulates in small increments.

Published
Reading time
43 min read
Category
Software design
Tags
Translated from
the Chinese original
Contents35 sections

This is the second post in my APOSD reading notes. The first one covered Chapter 1: the biggest limit on writing software is understanding, and there are two ways to deal with complexity—eliminating it and encapsulating it. Chapter 2 paints a portrait of this enemy: what it is, what it looks like, and where it comes from. The author says at the start of the chapter that it lays down some basic assumptions for the whole book; later chapters all take this chapter’s content as a premise and build refinements and inferences on top of it.

As with the previous post, the “From the book” sections are the book’s content, retold in my own words; English quotations are from the original. The rest—my reading, examples, and extensions—is my own addition.

The chapter in brief

As the book defines it, complexity is anything about a software system’s structure that makes the system hard to understand and change. It shows itself in three symptoms (change amplification, cognitive load, and unknown unknowns) and has two causes (dependency and obscurity). It is not the result of one big mistake but the sum of many small dependencies and small obscurities, hundreds or thousands of them. So the basic strategy for fighting it is: cut the number of dependencies, make the ones that remain obvious, reduce obscurity, and show zero tolerance for every “small” bit of complexity.

The line of argument

Text
[Motivation] To fight complexity, first know the enemy (identify before you treat)
   │        Recognizing complexity is itself a design skill: judging "is it simple" is easier than creating a simple design
   ▼
[Definition] Complexity = anything about a system's structure that gets in the way of understanding and changing it
   │     · Experienced by a developer "at a particular moment, for a particular goal"
   │     · Not necessarily related to size or number of features, but to "common activities": C = Σ (c_p × t_p)
   │     · More apparent to readers than to writers
   ▼
[Symptoms] ① Change amplification   ② Cognitive load   ③ Unknown unknowns (the worst)
   │
   ▼
[Causes] ① Dependency    ② Obscurity
   │      Dependency → change amplification + cognitive load
   │      Obscurity → unknown unknowns + cognitive load
   │
   ▼
[Pattern] Complexity is incremental: many small chunks accumulate, each seemingly harmless, and once accumulated they are hard to remove
   │
   ▼
[Conclusion] Systems become hard and risky to modify → "zero tolerance" is required (Chapter 3 develops this)

Section by section

Introduction: understand the enemy first

From the book

The book’s subject is designing software systems so that their complexity stays as low as possible, and the first step is to get to know the enemy: what complexity really is, how to tell whether a system is more complex than it needs to be, and how systems end up complex. This chapter answers these questions at a high level; later chapters then teach you to recognize complexity from concrete structural features.

Recognizing complexity is a crucial design skill: it lets you spot problems before investing a lot of effort, and it lets you choose well among alternatives.

It is easier to tell whether a design is simple than it is to create a simple design

But as long as you can tell that a system is too complex, you can use that ability to steer the design toward simplicity: if a design looks complex, try a different approach and see whether it becomes simpler. Over time, you will discover which techniques tend to produce simpler designs and which are associated with complexity, and you will produce simple designs faster and faster.

My reading

This passage implies an important methodology for learning: the path to better design is not “first learn how to produce good designs” but “first learn to recognize bad designs.” This forms a closed loop with section 1.1’s “recognizing red flags” and Chapter 11’s “Design it twice”:

  1. Produce a design;
  2. Examine it with this chapter’s list of symptoms;
  3. If it looks complex, try a different approach and compare;
  4. Over time, you will discover “which techniques tend to produce simple designs and which are associated with complexity,” and you will get faster.

“Recognizing a bad design is easier than producing a good one” is a very useful insight—it means review and comparison are the main means of learning design, not conjuring things up from nothing.

The definition of complexity (section 2.1 of the book)

From the book

The author defines complexity from a practical point of view:

Complexity is anything related to the structure of a software system that makes it hard to understand and modify the system.

There is also a cost-and-benefit way of looking at it: in a complex system, even a small improvement takes a lot of work, while in a simple system a smaller effort buys a bigger improvement. Complexity is experienced by a developer at a particular moment, for a particular goal, and it is not necessarily related to how big the system is overall or how many features it has.

Complexity is determined by the most common activities: if a system has a few places that are extremely complex but almost never need to be touched, they contribute little to overall complexity. The author uses a “crude mathematical way” to capture this:

C = Σ (c_p × t_p)

The total complexity C of a system equals the sum, over each part p, of that part’s complexity c_p multiplied by the fraction of time t_p developers spend working on that part. From this it follows that:

Isolating complexity in a place where it will never be seen is almost as good as eliminating the complexity entirely.

Finally, complexity is more apparent to readers than to writers:

Complexity is more apparent to readers than writers.

If code you wrote feels simple to you but complex to others, then it is complex. When this happens, it is worth asking others why they find it complex; the gap between your view and theirs probably holds something worth learning. A developer’s job is not just to write code that is convenient for themselves, but also code that is convenient for others.

My reading

This definition can be broken into five key judgments, each of which runs against common intuition:

#The author’s judgmentWhat it contradictsPractical implication
1Complexity is structure-related “hard to understand and modify”Intuition says complex = lots of code, hard algorithms, many featuresThe measure is “cost of change,” not “amount of code”
2Complexity is an experience relative to a goal and a momentIntuition says complexity is an inherent property of codeThe same code has different complexity for different tasks; evaluate from the “most common tasks”
3Complexity is determined by the most common activitiesIntuition says every part of the system matters equallyOptimization effort should go to the “hot spots”; isolate complexity where few people go
4Complexity is more apparent to readers than to writersIntuition says “if it’s clear to me, that’s enough”The evaluator should be someone else, not yourself
5The definition puts “hard to understand” and “hard to modify” togetherIntuition separates reading from changingReadability and maintainability cannot be separated (this is my own extension)

On the formula C = Σ c_p × t_p

This is one of the rare mathematical expressions in the book, and the author himself calls it only “a crude mathematical way.” Its value is not in precise calculation but in three insights that can directly guide decisions:

  • Put complex things where few people go. A regex engine, a protocol parser, or a crypto library may be extremely complex inside; as long as their interfaces are simple and they are rarely modified, they contribute little to the system’s total complexity. This is what “isolating complexity is almost as good as eliminating it” means—and it is the basis for Chapter 4’s “deep modules” and Chapter 8’s “pull complexity downwards.”
  • “Hot code” must stay simple. Business logic, frequently changed configuration, and often-reworked UI structure are where developers spend the most time; any obscurity there gets amplified by t_p.
  • Complexity’s “bill” is paid over time. A piece of complex code you don’t touch today is not free; its cost is deferred—with interest (see “Complexity is incremental” below and Chapter 3’s technical debt).

Additional examples

  • A database storage engine’s B+ tree implementation has tens of thousands of lines of extremely hard code, but application developers never touch it—to them it “almost doesn’t exist.” By contrast, a 30-line “utility function” that every business developer has to read every time they change a feature may contribute a much larger t_p × c_p.

Critical boundaries

  • “Common activities” change. A module that is rarely touched today may become a hot spot because of new requirements, and the complexity accumulated in the past will suddenly “come due.” The formula’s implicit remedy is therefore not “hide the bad code” but “encapsulate the complexity in a module with a clear interface and thorough tests”; if it becomes a hot spot, you only have to face the interface.
  • “Complexity is what readers find complex” needs a supplement. The judgment is correct, but the author does not say who the reader is—a newcomer, a seasoned maintainer, or yourself three months later? Different readers have different “baseline knowledge.” The workable approach is to have people unfamiliar with this code review it, and to seriously ask “why do you find this complex”—which is exactly what the author means by “worth asking others.”

The three symptoms of complexity (section 2.2 of the book)

Symptom one: change amplification

From the book

The first symptom: a change that looks simple means editing code in many different places. The book’s example is Figure 2.1: a website has many pages, and each one shows a banner with a background color. Many early sites hard-coded that color separately in every page (Figure 2.1(a)), so switching to a new color meant editing each page by hand, which was all but impossible for a site with several thousand pages. A modern site sets the color once, in one central place (the shared variable bannerBg in Figure 2.1(b)), and every page refers to it, so a single edit does the job. One thing good design tries to do is reduce how much code each design decision touches, so that changing the design doesn’t mean changing a lot of code.

My reading

Change amplification is the most visible symptom, because it shows up directly as workload. The key insight is in the last sentence: good design should reduce “how much code each design decision touches.” In other words, a decision should “live” in as few places as possible—this is the core of Chapter 5’s “information hiding”: encapsulate a decision inside one module, and let everything else depend on the interface rather than on the decision itself.

Additional examples (code below under “Change amplification: adding a field to User”)

  • Adding a field to User requires changing the database table, the ORM entity, the DTO, the serializer, the validator, the frontend type definitions… each of these is a copy of “the same decision.”
  • “Design tokens” in a design system: colors, spacing, and font sizes are defined once, and components only reference the tokens.

Critical note: duplication is not always bad

Some “duplication” is deliberate, traded for obviousness. Go requires every layer to explicitly write if err != nil { return err }; this is redundant, but it makes control flow obvious at a glance. The Go FAQ explains: “We believe that coupling exceptions to a control structure, as in the try-catch-finally idiom, results in convoluted code.” Another classic counterexample is “premature abstraction to eliminate duplication”: two pieces of code that happen to look similar but will actually evolve in different directions get forcibly merged into one function with five boolean parameters—the duplication is gone, but change amplification and cognitive load get worse. Sandi Metz sums this up as “duplication is far cheaper than the wrong abstraction.” So the more precise principle is: reduce change amplification caused by “the same design decision,” not eliminate all duplication.

Symptom two: cognitive load

From the book

The second symptom is cognitive load, the amount of knowledge a developer needs to finish a task. The higher it is, the longer developers have to spend picking up the information they need, and the greater the chance that they miss something important and cause a bug. The book’s example: a C function hands back a pointer to memory it has allocated and expects the caller to free that memory. This adds cognitive load for every developer who uses the function, and forgetting to free it causes a memory leak; if the code can be refactored so that the module that allocates the memory is also the one that frees it, callers no longer have to worry about it. Cognitive load has many sources: APIs with a large number of methods, global variables, inconsistency, and dependencies among modules.

The author also criticizes the view that complexity can be measured in lines of code. Some people think that the shorter an implementation is, the simpler it is, and that a change touching only a few lines must be easy, but this ignores what cognitive load costs. He has come across frameworks with which an application can be written in just a few lines, yet working out what those lines should be is extremely hard. Sometimes an approach that takes more lines turns out to be simpler, because it lowers cognitive load.

My reading

Cognitive load is the symptom closest to “the human brain”, directly echoing Chapter 1’s “keeping all the relevant factors in your head.” Cognitive Load Theory in cognitive science (proposed by Sweller in 1988) later divided load into three categories (Sweller, van Merriënboer & Paas 1998), which map well onto software:

TypeMeaningSoftware counterpartCan it be reduced?
Intrinsic loadThe inherent, irreducible difficulty of the task itselfThe inherent complexity of business rules, the difficulty of the algorithm itselfAlmost not; can only be decomposed
Extraneous loadBurden introduced by the presentation, unrelated to the taskVague names, inconsistencies, implicit conventions, “freeing obligations” to remember, magic frameworksYes, and this is the main battlefield of design
Germane loadEffort spent building a mental modelUnderstanding domain concepts, forming a picture of the whole systemShould be supported, not eliminated

Note: the three-way classification comes from the 1998 follow-up paper, not Sweller’s 1988 original; Sweller later also stopped treating germane load as a separate category. I borrow the three categories here only to illustrate the difference between “extraneous load” and “intrinsic load.”

This table yields an important corollary: software design is mainly a fight against “extraneous load”—it is almost entirely accidental complexity (in Brooks’s sense), caused by the “presentation,” and therefore removable by design.

Three forms of the “lines of code” fallacy (code below under “Cognitive load: three kinds of short but heavy code”)

  1. One-line fluent expressions / regexes: solved in one line, but the reader spends minutes expanding it in their head.
  2. Magic frameworks / metaprogramming: has_many :comments, annotation-driven auto-wiring, convention over configuration—only a few lines of code, but you must know “what happens behind these lines.”
  3. Implicit contracts: units (milliseconds or seconds?), time zones, encodings, ownership—the code is short, but the contract is long.

Symptom three: unknown unknowns—the worst kind

From the book

The third symptom: it is unclear which code you need to change to get a task done, or what information you need to get it right. Figure 2.1(c) is the example: the banner’s background color is already defined centrally, but some pages also emphasize things with a darker color, which each of those pages hard-codes on its own. Any change to the background color calls for a matching change to the emphasis color, but the developer will most likely not realize this; and even if they do, they won’t know where the emphasis color is used, so their only option is to search the entire site.

The author considers unknown unknowns the worst of the three symptoms: you need some piece of knowledge, but have no means of learning what it is, or even of telling whether a problem exists; often you only discover it when a bug shows up after the change. Change amplification is irritating, but if you know which code to change, the system will work once you’ve made the changes. High cognitive load makes a change more expensive, but if you know which information you need to read, the change will most likely still be correct. With unknown unknowns, you don’t know what you should do, nor whether your solution will work; the only way to be sure would be to read all of the system’s code, line by line, which no one can do for a system of even modest size. On top of that, the change may hinge on some subtle design decision that nobody ever wrote down.

That is why making a system obvious is one of the top goals of good design: a developer can quickly see how the current code works and what a change would involve, can guess what to do without thinking hard about it, and can trust that the guess is right.

My reading

The three symptoms can be arranged on a ladder by “how much you know”:

SymptomDo you know where to change?Do you know what to learn?NatureConsequence
Change amplificationYes, but many placesYesTiringSlow, but can be done right
Cognitive loadYesYes, but a lotExpensiveSlow, may miss something
Unknown unknownsNoDon’t know what you don’t knowDangerousMay change the wrong thing without realizing

In other words, the first two are “known hard,” the third is “unknown danger.” Their essential difference is whether there is a signal: change amplification at least tells you where to look and search gives results; cognitive load has documentation and signatures as signals; unknown unknowns have no signal at all—until a bug appears.

What causes unknown unknowns? Almost always implicit dependencies—the combination of “dependency + obscurity” discussed under “The two causes” below:

  • Global mutable state: who changed it, and when?
  • Shared databases: another service writes directly to your table.
  • Initialization order, temporal coupling: A must happen before B, but nothing says so anywhere.
  • Reflection, dependency injection, dynamic dispatch: you can’t see the implementation when you jump to it.
  • Cross-page “visual consistency”—the Figure 2.1(c) example, a kind of “data-level implicit dependency.”
  • Design decisions that were never written down.

How to eliminate them? The core means is “making the implicit explicit,” turning dependencies into things tools or readers can see:

MeansPrincipleRelated chapters
Single source of truth + derived valuesLet “related values” be computed from one source; the dependency becomes codeChapters 5, 6
Compiler / type systemTurn dependencies into compile errorsSection 2.3 of the book
Make illegal states unrepresentableTurn “conventions you must remember” into type constraintsClose to Chapter 10’s idea
Consistent naming and conventionsLet readers “guess correctly”Chapters 14, 17, 18
Write down cross-module design decisionsMake “never-recorded decisions” visibleSection 13.7 of the book
TestsLet “unknown dependencies” signal when a change happensChapter 19

The “thorough fix” for Figure 2.1(c): the emphasis color should never have been an independent value; it is a derived value of the banner color. Change the hard-coded emph = "darkred" on a few pages to darken(bannerBg), and the knowledge that “the emphasis color must follow the banner color” becomes the code itself—the unknown unknown ceases to exist. This is the same idea as the book’s point that the best way to cut down on obscurity is to make the system’s design simpler: the best documentation is making a fact no longer need to be remembered.

The two causes of complexity (section 2.3 of the book)

Cause one: dependency

From the book

In this book, a dependency means that a piece of code can’t be understood and changed on its own: it is connected to other code in some way, so when you change it you have to consider that other code, or change it as well. The book gives three examples: the pages of a website (which all show the same background color); the sender and the receiver of a network protocol (each side has its own code, but both have to follow the protocol, so a change on one side almost always calls for a change on the other); and method signatures (add a parameter to a method, and every call site has to be updated).

Dependencies are a basic part of software and cannot be completely eliminated. Indeed, we deliberately introduce dependencies as we design: every time we write a new class, we create dependencies around its API. One goal of software design is to have fewer dependencies, and to keep the ones that are left as simple and obvious as they can be.

Back to the website example: the old website wrote the background color separately in every page, so all pages depended on each other; the new website defines the color centrally and provides an API for pages to fetch at render time, eliminating the dependencies between pages but creating a new dependency around this color-fetching API. Fortunately, the new dependency is more obvious: every page clearly depends on bannerBg, and a search by name finds all uses; the compiler also helps—if the shared variable is renamed, all code still using the old name fails to compile. The author’s summary: the new website replaced an unobvious, hard-to-manage dependency with a simpler, more obvious one.

My reading

There is an easily overlooked claim in this passage: the new website eliminated the dependencies between pages, and at the same time created a new dependency around the color-fetching API. The author’s focus is on replacing an unobvious dependency with a more obvious, better-managed one. The number of dependencies certainly went down too (originally pages depended on each other pairwise), but what matters more is whether the remaining dependencies can be seen, searched, and checked by the compiler. This is one of the book’s core strategies: dependencies cannot be fully eliminated, so reduce their number while making the remaining ones visible, findable, and checkable by tools.

Dependencies can be arranged on a spectrum by “degree of visibility”:

VisibilityForm of dependencyExampleWho helps you find it
Most obviousCompiler-checkable dependencyFunction signatures, types, variable namesCompiler / IDE
ObviousSearchable dependencyConfigurations and constants findable by nameText search
DimmerRequires reading docs/comments to know“The caller is responsible for freeing”, “unit is milliseconds”Documentation (Chapter 13)
DarkTemporal dependencyMust call init() before start()Nobody
DarkerData/semantic dependencyThe two ends of a protocol, the color relationship in Figure 2.1(c)Nobody
DarkestEnvironmental dependencyGlobal state, runtime configuration, another service writing to your databaseNobody

The goal of design is to “push the dark ones upward”: if the compiler can check it, don’t write documentation; if it can be written into code, don’t rely on convention; if it can be a derived value, don’t rely on people remembering.

Extension: connascence—a “strength scale” for dependencies

Meilir Page-Jones proposed a finer-grained concept in the 1990s: connascence. The idea: two components are connascent if changing one requires changing the other to keep the whole system correct. As organized by connascence.io, the static forms include coupling by name (must use the same name), type, meaning (e.g. magic numbers must agree; using a named constant reduces this to name coupling), position (parameter order), and algorithm (each side implements the same algorithm, e.g. a checksum); the dynamic forms include execution (must be called in order), timing (must happen within a certain time), value (runtime values must agree), and identity (must share the same instance). The claim there is: “Stronger connascences are harder to discover, or harder to refactor.” This classification has a very useful property: the earlier forms are weak, obvious, and easily checked by tools; the later forms are strong, obscure, and invisible. Good design should convert strong dependencies into weak ones as much as possible. This is fully consistent with Ousterhout’s goal of keeping the remaining dependencies as simple and obvious as they can be, and it provides a concrete scale for “simple/obvious.”

Cause two: obscurity

From the book

The second cause is obscurity: important information is not obvious. The simplest example is a variable name that is too generic, like time, which carries almost no useful information; or a variable whose documentation doesn’t state its units, forcing you to read through all the code that uses it to guess. Obscurity often appears together with dependency, in the form of a dependency that exists but is not obvious: for example, adding a new error status code to a system may require adding an entry to a “status → message” string table, but someone looking at the status code declaration may not know that table exists. Inconsistency is also a major source of obscurity: the same variable name used for two purposes, so the reader can’t tell which one applies in a given place.

In many cases, obscurity comes from documentation that isn’t good enough (Chapter 13 is devoted to this), but obscurity is also a design problem: a system whose design is clean and obvious needs less documentation. Often, needing a lot of documentation is a red flag that something in the design is still a little off; the best way to cut down on obscurity is to make the system’s design simpler.

My reading

Is time the creation time, the modification time, or the timeout? Are the units seconds or milliseconds? Names and units, two small things, are the most common entry points for obscurity (code below under “Obscurity: units, naming, and inconsistency”).

How the causes map to the symptoms

From the book

Between them, dependency and obscurity account for all three symptoms: dependency leads both to change amplification and to high cognitive load, while obscurity gives rise to unknown unknowns and also adds to cognitive load.

Change amplificationCognitive loadUnknown unknowns
DependencyYes (many dependencies, one change touches many places)Yes (many dependencies, much to learn)(If the dependency is obscure)
ObscurityYes (information not obvious, takes effort to figure out)Yes (don’t know there is information to know)

My reading: the different natures of the two causes

This matrix is worth dwelling on, because dependency and obscurity are completely different in how governable they are:

  • A good part of dependency is essential. The sender and receiver must obey the same protocol; a method and its callers must agree on a signature—these dependencies are determined by the problem itself. You can only make them fewer and more obvious, not eliminate them.
  • Obscurity is almost entirely accidental. Vague names, missing units, inconsistent conventions, unrecorded decisions—none of these is required by the problem itself. Fighting obscurity is therefore the highest-return investment: it requires almost no trade-off, only care.

Another important corollary: “dependency + obscurity” = unknown unknowns. Dependency by itself only means “several places must be considered together”; once that dependency is also unobvious, it escalates from “trouble” to “danger.” So the highest priority is obscure dependencies—temporal coupling, implicit conventions, cross-module decisions.

“Often, needing a lot of documentation is a red flag that something in the design is off”

This sentence seems to belittle documentation, but it actually puts pressure on design: when you find code that “can’t be understood without comments,” your first reaction should not be “add comments” but “can the design be changed so it doesn’t need comments.” Chapter 13 explains what kinds of information code cannot express and must be written as comments (such as why, and cross-module conventions); the rest of the obscurity should be eliminated through design.

Complexity is incremental (section 2.4 of the book)

From the book

Complexity isn’t caused by a single catastrophic error; it accumulates in lots of small chunks.

A single dependency or a single spot of obscurity is, on its own, unlikely to make a significant difference to how maintainable a system is. Complexity comes from small dependencies and small obscurities, hundreds or thousands of them, piling up over time, until there are so many that a few of them will affect any change you might make to the system. Because it is incremental, complexity is hard to keep under control: you can easily talk yourself into believing that the bit of complexity your current change brings in is no big deal, but if every developer reasons that way about every change, complexity builds up fast. And once it has built up, it is hard to get rid of, since fixing any one dependency or one spot of obscurity brings no visible improvement by itself. Slowing the growth of complexity takes an attitude of “zero tolerance”; Chapter 3 expands on it.

My reading

This section takes Chapter 1’s “complexity is inevitable” a step further and reveals an asymmetric structure—complexity works against us in both directions:

  • When adding it: each step is small and easy to justify. “It’s just one more if”, “let’s leave it for now, we’ll fix it next iteration.”
  • When removing it: each step yields little and is hard to motivate. Fix one dependency, and the system doesn’t get noticeably better.

I think this resembles a tragedy of the commons (Hardin 1968): “Ruin is the destination toward which all men rush, each pursuing his own best interest in a society that believes in the freedom of the commons.” Each developer takes a shortcut for their current task, and the cost is borne by everyone; the cost of cleanup is borne by the cleaner alone, while the benefit is shared by all. The result is that nobody cleans up. The author’s answer in Chapter 3 is “zero tolerance”—not accepting “needless complexity introduced to meet a deadline”, even when it is small.

Three complementary metaphors

MetaphorSourceOriginal wordsWhat it emphasizes
Technical debtWard Cunningham, OOPSLA 1992See the Chapter 3 notesShortcuts are like borrowing money: faster in the short term, principal plus interest in the long term—explains why “fix it later” gets more and more expensive
Broken windowsWilson & Kelling, The Atlantic 1982; borrowed by The Pragmatic Programmer“Don’t leave ‘broken windows’ (bad designs, wrong decisions, or poor code) unrepaired. Fix each one as soon as it is discovered. If there is insufficient time to fix it properly, then board it up.”An unrepaired broken window signals “nobody cares here”—explains complexity’s social contagion: one ugly spot lowers the psychological threshold for the next shortcut
Boiling a frogCommon metaphor—Gradual change goes unnoticed—explains why “nobody noticed when the system went bad”

The tension between “zero tolerance” and “moderation”

Section 1.1 of the book emphasizes that “every principle has limits, and taking it to an extreme leads to a bad place”; this section says to have “zero tolerance” for complexity. Are the two contradictory? Chapter 3 shows they are not; the key is what zero tolerance targets:

  • Zero tolerance targets “needless complexity introduced to save a few minutes”—a casually added global variable, a vague name, a special case that could have been eliminated, an unwritten convention. These can be avoided with almost no trade-off.
  • Moderation applies to how principles are applied—building a giant class in the name of “deep modules,” masking real errors in the name of “defining errors out of existence,” making the wrong abstraction in the name of “eliminating duplication.”

In other words: zero tolerance for “accidental complexity,” judgment in “how principles are executed.”

Conclusion (section 2.5 of the book)

From the book

Complexity comes from dependencies and obscurity building up. As it grows, it brings change amplification, a heavier cognitive load, and unknown unknowns: each new feature takes more code changes to implement; developers need longer to collect enough information to change things safely, and at worst they cannot even track down everything they need to know. In the end, complexity makes changing existing code both difficult and risky.

My reading

“Difficult” corresponds to cost (the first two symptoms); “risky” corresponds to unknown unknowns.

A few points worth thinking about further

Complexity is “relative to the reader”—which creates a measurement problem

One of the deep points of this chapter’s definition is that complexity is defined as a developer’s experience at a moment, not an inherent property of code. This means:

  • There is no objective measure of complexity. Cyclomatic complexity, lines of code, and coupling metrics can only capture the “structural” side; they cannot capture “what the reader needs to know” and “what the reader doesn’t know they don’t know.”
  • The same code has different complexity for different teams. An ownership model that is obvious to a Rust team is a huge cognitive load for a team just migrating from Java.
  • The workable alternative is “proxy metrics”: onboarding time for newcomers, time to first PR, how many files a typical requirement touches (a proxy for change amplification), how many production incidents are attributed to “we didn’t know something else depended on it” (a proxy for unknown unknowns).

A practical suggestion: treat newcomers as complexity detectors. They don’t have the author’s “background knowledge”; the places where they get stuck are the most obscure parts of the system—this is exactly the application of the author’s “complexity is more apparent to readers.”

The deeper layer of the “lines of code” fallacy: short is not simple, long is not complex

In the author’s framework example, the application code is only a few lines; the hard part is figuring out which few lines to write: the cognitive load falls on the person writing the application (I suspect because they must first understand a large pile of implicit conventions behind the framework). The same fallacy also costs the people reading the code, and it can be split into two opposite errors:

  • Treating “short to write” as “simple to read”: metaprogramming, annotation magic, one-line regexes. The writer saves time; the reader pays the cognitive load—this shifts the cost onto the reader, consistent with Spolsky’s “reading code is harder than writing it.”
  • Treating “long to write” as “bad design”: explicit type declarations, repeated error handling, verbose but unambiguous configuration. This “length” buys obviousness—the compiler can check it, and the reader understands at a glance.

The right standard of comparison is how much you need to know to complete a task, not the physical length of the code.

Dependencies cannot be fully eliminated—so “obvious” is crucial

Perhaps the most important practical strategy in this chapter is the summary of the website example: replace an unobvious, hard-to-manage dependency with a simpler, more obvious one. This means:

  • When evaluating a change, don’t just ask “are there fewer dependencies?”; also ask “are the remaining dependencies more obvious and more checkable by tools?”
  • The compiler, the type system, and the IDE are “dependency management tools”—dependencies they can manage should not be left to human memory. This is also a structural reason static typing is popular in large systems.
  • A converse corollary: the more dynamic/implicit features a system has, the more unknown unknowns it has—reflection, monkey patching, runtime configuration, global state. They are not unusable, but if you use them you must add explicit documentation or tests to “illuminate” them.

The boundaries of “isolating complexity is almost as good as eliminating it”

C = Σ c_p × t_p supports isolating complexity where few people go. But note three things:

  1. t_p is not a constant. Requirement changes can turn a cold module hot.
  2. Isolation requires an interface and tests as prerequisites; otherwise the complexity is just “moved somewhere out of sight,” and when something goes wrong (say, a 3 a.m. production incident), it becomes the hottest code—and the most obscure.
  3. Isolation is not concealment. Hiding an obscure dependency inside a module nobody understands does not reduce unknown unknowns; it only postpones them.

Extensions and additional examples

Change amplification: adding a field to User

Text
Requirement: add a "nickname" to users.

Change list:
  1. Database schema        ALTER TABLE users ADD nickname
  2. ORM entity             User.java +1 field
  3. DTO                    UserDto +1 field
  4. Serialization          Jackson annotation or manual mapping +1
  5. Validator              NicknameValidator (length, sensitive words)
  6. API documentation      OpenAPI definition
  7. Frontend types         user.d.ts
  8. Form / detail page     two UI components

Eight changes, and one decision (“users have a nickname”) copied eight times. Each one looks “reasonable” on its own; together they are change amplification. The way to reduce it is not “eliminate layers” but describe the same decision only once: use schema-first code generation (generate entities, DTOs, and frontend types from OpenAPI / IDL), or let the ORM/serialization derive from a single definition.

Cognitive load: three kinds of “short but heavy” code

Java
// (1) One-line fluent: short, but you have to expand three steps in your head
int secondHighest = nums.stream().distinct().sorted(Comparator.reverseOrder())
                        .skip(1).findFirst().orElse(-1);

// (2) Implicit units: short code, long contract
schedule(task, 5000);           // Is 5000 milliseconds? Seconds? Measured from when?

// (3) Implicit ownership: the classic C example; the caller must remember free()
char *buf = read_all(path);     // Who frees it? The caller. But nothing enforces it

Designs that reduce the load:

Java
// (1) A small named method makes the "intent" explicit—more lines, less load
int secondHighest(List<Integer> nums) {
    List<Integer> distinctDesc = nums.stream().distinct()
                               .sorted(Comparator.reverseOrder())
                               .collect(toList());
    return distinctDesc.size() >= 2 ? distinctDesc.get(1) : -1;
}

// (2) Put the unit into the type
void schedule(Runnable task, Duration delay);
schedule(task, Duration.ofSeconds(5));

// (3) Hand "freeing" to a language mechanism
try (InputStream in = Files.newInputStream(path)) { ... }   // Java: freeing written in one place, not missed on exception paths
// Rust: values are freed automatically when they leave scope; ownership rules are checked by the compiler

(3) is exactly the author’s C example—the book says letting the module that allocates memory also be responsible for freeing it reduces cognitive load. Modern languages go further: Rust’s ownership and C++‘s RAII turn this convention into a language rule guaranteed by the compiler; Java’s try-with-resources and Python’s with shrink “remember to free” into a fixed idiom.

Unknown unknowns: fixing Figure 2.1(c)

In Figure 2.1(c), the banner color is "red", and a few pages hard-code a darker emphasis color "darkred":

Text
Version (c): looks centralized, but has one implicit dependency
  bannerBg = "red"                 ← defined centrally, referenced by all pages   ✔
  A few pages: emph = "darkred"    ← emphasis color hard-coded per page           ✘

  Change bannerBg → the emphasis color is no longer "darker" → visual inconsistency, and nobody knows which pages to change.
Text
Fix: make the emphasis color a derived value—the dependency goes from "remembered by people" to "a fact in the code"
  bannerBg = "red"
  emphBg   = darken(bannerBg)        ← single source of truth + derivation
  Pages needing emphasis all reference emphBg

Similar “implicit dependencies” in other domains:

ScenarioImplicit dependencyWay to make it explicit
Multiple services write the same tableOthers don’t know your schema constraintsSingle writer / event bus / schema contract tests
Must call init() before start()Temporal couplingInitialize in the constructor, or use state machine types
Cache invalidationDon’t know who changed the underlying dataRoute all writes through one module
Global switchesDon’t know which behaviors are affectedInject the switch as an explicit parameter / config object
Time zonesWhether “time” is local or UTCDistinguish types LocalDateTime / Instant

Dependency: converting strong dependencies into weak ones

Java
// Strong dependency (position + meaning): the caller must remember the parameter order and what 30, 1000, true each mean
socket.setTimeout(30, 1000, true);

// Weak dependency (name + type): each value carries a name and a unit; a reader can spot a swap at a glance
socket.setTimeouts(Timeouts.builder()
        .connectTimeout(Duration.ofSeconds(30))
        .readTimeout(Duration.ofSeconds(1))
        .retryOnTimeout(true)
        .build());

If you only change the parameters to Timeout.of(Duration, Duration, Retry), swapping the two Durations still compiles, and the positional coupling remains. The essence of “weakening a dependency” is: the content of the dependency changes from “knowledge a person must remember” to “a form tools can check and readers can see at a glance.”

Obscurity: units, naming, and inconsistency

Java
// Obscure naming
long time = System.currentTimeMillis() - start;
int  count;

// Inconsistent naming: one concept, two names
class Order  { List<LineItem> items; }
class Invoice{ List<Item> lines; }         // items / lines / LineItem / Item—are they the same thing?

// Inconsistent usage: one name, two meanings
int duration;       // seconds in class A, milliseconds in class B

A real-world “obscurity” disaster: NASA’s Mars Climate Orbiter (1999). The accident investigation board identified the root cause as “the failure to use metric units in the coding of a ground software file, ‘Small Forces,’ used in trajectory models”: the interface specification required this ground software file to output metric newton-seconds, but it output imperial pound-force-seconds; the navigation team used the data as metric per the specification, so the thruster impulses were underestimated by a factor of about 4.45. The error accumulated throughout the cruise, and the spacecraft ended up about 57 kilometers from the Martian surface before contact was lost. The units were actually written in the interface specification; the problem was that they were only in the specification: the data itself carried no units, and nothing anywhere reported the mismatch. Important information that is not obvious becomes an unknown unknown.

The engineering counterpart is putting units into types (Duration, Temperature, Meters), turning “unit mismatch” into a compile error instead of an accident report.

Incremental: a timeline of “small concessions”

Text
Week 1   "Let's add a global variable for the current user; we'll change it to injection later."        (+1 global state)
Week 3   "This interface is missing a parameter; pass it through ThreadLocal for now."                  (+1 implicit dependency)
Week 6   "This logic is similar to that one but a bit different; copy it and tweak it."                 (+1 duplication)
Week 9   "Temporarily add an if to check whether the user is an admin."                                 (+1 special case)
Week 12  Newcomer: "Why do I have to read all five files to change this feature?"
         Veteran: "That's just how it grew; nobody knows why."                                          (unknown unknowns)

Each step looks like “just a small thing” on its own, but none of them is a “catastrophic error.” This is exactly what section 2.4 of the book calls “the accumulation of many small chunks.”

Connections to other ideas

IdeaKey pointRelation to this chapter
Brooks: essential vs. accidental complexityEssential complexity cannot be eliminated; accidental complexity canA good part of this chapter’s “dependency” is essential (protocol endpoints, method signatures); “obscurity” is almost entirely accidental—so governing obscurity is the highest-return investment
Parnas: information hidingModules should be organized around “design decisions likely to change”This chapter’s “reduce how much code each design decision touches” is a direct statement of information hiding; Chapter 5 develops it
Cognitive Load Theory (Sweller)Intrinsic / extraneous / germane loadThis chapter’s cognitive load is mainly “extraneous load”—exactly the part design can remove
Connascence (Page-Jones)Dependencies graded by strength; weak dependencies beat strong onesProvides a concrete scale for “make dependencies simple and obvious”
Coupling / cohesion (Yourdon & Constantine)Looser coupling and stronger cohesion are betterShares roots with the concept of “dependency”; Ousterhout’s contribution is emphasizing obviousness, not just quantity
Fowler: code smells“Shotgun surgery” = one change touches many placesThis is this chapter’s “change amplification”
Metz: the wrong abstraction“duplication is far cheaper than the wrong abstraction”Draws a boundary for “reducing change amplification”: don’t make the wrong abstraction to eliminate duplication
Technical debt (Cunningham)Shortcuts = debt, with interestExplains “why it gets harder to remove later” in the “complexity is incremental” section; Chapter 3 discusses it head-on
Broken windows (Wilson & Kelling) / The Pragmatic ProgrammerSmall disorder is contagiousExplains “why every small concession is not innocent”
McCabe cyclomatic complexity / various complexity metricsMeasures control-flow branches; McCabe’s original paper also says “complexity is independent of physical size … depends only on the decision structure of a program”Captures “local structure” only; cannot capture cognitive load and unknown unknowns—this chapter’s definition explains why these metrics fall short
Tragedy of the commons (Hardin)Individual rationality leads to collective irrationalityExplains why “zero tolerance” needs to be a team institution, not just personal discipline

Disputes and criticisms

DisputeThis chapter’s positionThe challengeMy assessment
Can complexity be defined?“Hard to understand and modify” is a practical definitionThe definition is subjective, relative to the reader, and unmeasurableThe author explicitly says this is a practical definition; the cost is difficulty of quantification, the benefit is closeness to engineers’ real experience
Is “zero tolerance” realistic?Zero tolerance for small complexityImpossible to achieve every time under delivery pressureChapter 3 gives a workable answer with “10–20% investment”; though this ratio is the author’s suggestion, the book gives no data for it, and the author also explicitly says he has no data on the exact shape of the investment-return curve or the payback time
Unknown unknowns are the worstThe worst, since you can’t discover themToo pessimistic: tests, types, and reviews can all turn many “unknowns” into “knowns”The author is not pessimistic: he says making the system obvious is one of the top goals of good design, and an obvious system is exactly the reverse of a heavy cognitive load and of unknown unknowns; section 4.2 of the book also says that spelling out an interface clearly helps eliminate unknown unknowns
Lines of code ≠ complexityAgainst measuring by lines of codeNo alternative metric offeredThis is a real gap; the industry still mainly uses proxy metrics
“Needing a lot of documentation often means the design is wrong”Rely on design to eliminate obscurity as much as possibleSome essential complexity (protocols, domain rules) genuinely needs a lot of documentationThe author explicitly supports writing comments in Chapters 12 and 13; what he opposes is using documentation to patch design problems
Disagreement with Clean CodeExplicit, obvious code may be longerClean Code emphasizes “smallness” moreConsistent with the debates in sections 9.8 and 12.6 of the book; this chapter’s “sometimes more code is simpler” is the theoretical root of this disagreement

Checklist: diagnose your system with this chapter’s framework

Diagnosis: the three symptoms

  • How many files did the last “seemingly simple” requirement touch? (change amplification)
  • How much did you have to read, and how many conventions did you have to remember, to complete it? (cognitive load)
  • Was there a time when you only discovered after a change that “something else depended on it”? (unknown unknowns)

Diagnosis: the two causes

  • Can this code be understood and modified in isolation? If not, where are the dependencies? Are they compiler-visible, or remembered by people?
  • Which information is important but not obvious? Names, units, timing, ownership, cross-module conventions?

Treatment: push the dark ones upward

  • Turn “conventions remembered by people” into things types / the compiler can check
  • Turn “related values” into values derived from a single source
  • Write down “design decisions never recorded” (or change the design so they don’t need to exist)
  • Use one consistent name for one concept; don’t use one name for two concepts
  • Keep zero tolerance for small concessions made “to meet the deadline”—at least record them and plan to clean up

Prevention: keep complexity in “cold” places

  • Does the complex implementation have a clear, narrow interface wrapping it?
  • Does it have tests, so there is a safety net when it “heats up”?

Key terms

EnglishChineseMeaning in this chapter
complexity复杂性Anything about a system’s structure that gets in the way of understanding and changing it
change amplification变更放大A seemingly simple change requires modifying code in many places
cognitive load认知负荷How much a developer needs to know to complete a task
unknown unknowns未知的未知Not knowing which code to change, nor what information is needed; the most dangerous symptom
obvious system明显的系统Developers can quickly and confidently guess what to do
dependency依赖A piece of code that can’t be understood and changed on its own; other code has to be taken into account
obscurity晦涩Important information is not obvious
inconsistency不一致One name for different things / different names for the same thing; a major source of obscurity
zero tolerance零容忍Not accepting any needless complexity introduced “for the current task” (Chapter 3)
C = Σ c_p × t_p—Total complexity ≈ the sum of each part’s complexity × the fraction of developer time spent on it
connascence同生性A strength scale for dependencies (extension concept)

Questions to think about

  1. State this chapter’s definition of complexity in one sentence, and explain why it is “not necessarily related to system size.” Give an example of something “small but complex” and something “large but simple.”
  2. Why does the author weight each part’s complexity by the time fraction t_p? What does this formula suggest about where to focus effort? What are its limitations?
  3. What is the relationship among the three symptoms? Why are “unknown unknowns” the worst? Describe an unknown unknown you have personally experienced.
  4. The author says dependencies “cannot be completely eliminated.” Is this right? Is there code with “no dependencies at all”? Why does the author say we “deliberately introduce dependencies”?
  5. The new website replaced one dependency with another. Why does the author say it is better? How does this affect your criteria for evaluating designs?
  6. “Often, needing a lot of documentation is a red flag that something in the design is off”—does this contradict Chapter 12’s “you should write comments”? Where does the boundary lie?
  7. Does “zero tolerance” contradict Chapter 1’s “don’t take things to extremes”? What does each apply to?
  8. Pick the most frequently modified module in your codebase, score it 1–5 on each of the three symptoms, and identify the corresponding dependencies and obscurities.
  9. Can metrics like cyclomatic complexity and lines of code capture the complexity defined in this chapter? If not, what proxy metrics would you use?

Next

This chapter says complexity accumulates incrementally and requires “zero tolerance,” but it doesn’t answer a practical question: under delivery pressure, how can you possibly get every step right? The Chapter 3 notes cover the author’s answer: distinguish tactical from strategic programming, treat design as an investment, and set aside roughly 10–20% of your time.

Principles

  • Complexity is incremental: you have to sweat the small stuff (item 1 in the book’s summary table of principles, from section 2.4 of the book)

Related red flags

The entries in the book’s red flag table only appear in later chapters; from this chapter’s perspective, many of them are specific forms of dependency or obscurity, for example:

  • Information Leakage: the same design decision reflected in multiple modules—a kind of dependency, manifesting as change amplification.
  • Repetition: a nontrivial piece of code appearing again and again—also causes change amplification.
  • Vague Name: a name too imprecise to convey much useful information—obscurity.
  • Nonobvious Code: code whose behavior or meaning is not easy to understand—obscurity, and in severe cases unknown unknowns.

Sources

The book

  • John K. Ousterhout, A Philosophy of Software Design, 2nd Edition, Yaknyam Press, 2021: Chapter 2 (2.1–2.5), Figure 2.1, the book’s summary tables of principles and red flags

Cognitive load and metrics

  • Sweller, J. (1988). Cognitive load during problem solving: Effects on learning. Cognitive Science, 12(2), 257–285. https://www.sciencedirect.com/science/article/pii/0364021388900237
  • Sweller, van Merriënboer & Paas (1998). Cognitive architecture and instructional design. Educational Psychology Review, 10(3), 251–296. (Source of the intrinsic / extraneous / germane classification)
  • McCabe, T. J. (1976). A Complexity Measure. IEEE Transactions on Software Engineering, SE-2(4), 308–320. DOI 10.1109/TSE.1976.233837

Classifying dependencies

  • Page-Jones, M. (1996). What Every Programmer Should Know About Object-Oriented Design. Dorset House.
  • connascence.io (the graded organization of connascence): https://connascence.io/
  • Yourdon, E. & Constantine, L. L. (1979). Structured Design: Fundamentals of a Discipline of Computer Program and Systems Design. Prentice Hall. (The coupling / cohesion classification; the concepts first appeared in Stevens, Myers & Constantine 1974, IBM Systems Journal 13(2))

Cases and metaphors

Languages and tools