Good code design keeps the next change cheap and safe: put what changes together behind a small interface that hides a lot (high cohesion, low coupling, deep modules), let dependencies point toward the stable rules and keep I/O at the edges, and change structure only in small steps that tests pin down.
Fig. 1 is that idea on real code: the busiest endpoint of the chat API built on Building a backend API, before and after the ten-step refactor of section 9. Each slab is one line of the handler, as long as the line and indented as in the file, coloured by the concern it serves (by keyword rules, so a line or two is approximate).
Why this is the whole subject. Code is read far more often than it is written (PEP 8 credits the insight to Guido van Rossum), so the test of a design is the next change: code that works today but makes every change risky is bad code; code that is a little longer but where each change touches one place is good code. Every section below is one technique for that, with what it costs and when not to use it.
You need: Python and a little FastAPI; nothing else. Elsewhere: tests themselves are Testing and quality's (doubles, CI, mutation testing); language idioms, typing mechanics and the toolchain (ruff, uv, type checkers, packaging) are Python: typing, uv, packaging and the toolchain's; whole-system design is System design case studies'; HTTP API design is Service APIs', and the service behind it Building a backend API's.
John Ousterhout, who teaches software design at Stanford, defines complexity as "Anything related to the structure of a system that makes it hard to work on the development of that system" (his course notes; the book is A Philosophy of Software Design, 2nd edition July 2021). Its three symptoms: change amplification (a simple change needs many edits), cognitive load (you must hold a lot in your head to make a change) and unknown unknowns (something you needed to know was not obvious, or not even findable). Its two causes: dependencies (if one piece changes, another must too) and obscurity (it is not clear how or why the code works). It is "judged by readers of code, not the writer", and it is incremental: "an accumulation of thousands of small dependencies and obscurities".
The older vocabulary for the same thing is cohesion and coupling, from Stevens, Myers and Constantine, "Structured design" (IBM Systems Journal 13(2), 1974; Constantine had used the terms since the late 1960s). Paraphrased: a module is cohesive when everything in it serves one purpose, so a change of that purpose touches one place; two modules are coupled when one depends on the other's insides, so changing one forces a change in the other. Aim for high cohesion and low coupling. In the hero figure the "before" handler has low cohesion: auth, rate limiting, idempotency, storage and the model call interleave, so changing the idempotency rule means finding its lines in five places. Coupling is the cause Ousterhout calls dependencies; low cohesion produces his change amplification and cognitive load.
Kent Beck's four rules of simple design, in priority order, compress the goal (Fowler's summary, 2015): passes the tests, reveals intention, no duplication, fewest elements.
POST /v1/chats/{id}/messages, is one 52-line function that checks the API key, applies a rate limit, handles idempotency keys, stores the message, charges credits and "calls the model". It works, and it is exactly the kind of function that becomes hard to change. A second example, an LLM call that titles and summarises a chat, was written for this page in the tangled shape such code usually grows into.PEP 8 fixes the spelling (lower_case_with_underscores functions, CapWords classes, ALL_CAPS constants, a leading underscore as the "weak internal use indicator"), and a formatter enforces it. The hard part is what a name says:
req_hash = hashlib.sha256(...); the refactor names the idea request_fingerprint(chat_id, body), so a reader learns what it is for (deciding whether two requests are "the same") without reading the hashing.timeout_s, max_chars, refill_per_s. A bare timeout=30 leaves every reader guessing: seconds or milliseconds?is_retryable, has_more), functions as verbs (claim_key, release_key, save_reply).r is fine for a response used on the next two lines; a module-level name must stand alone. data, info, manager, handle and process say almost nothing; they usually mean the thing has no single job yet.A function should either say what happens in a few named steps, or do one of those steps in detail. Mixing the two forces the reader to switch between "the plan" and "the SQL" every few lines. Toggle the real handler (right): before, the rate-limit lines sit between the auth lines and the idempotency lines; after, each concern is one named line and the details live in functions you open only when you need them.
Code says what; a comment earns its place by saying what the code cannot: why, what it protects against, what was tried and rejected. PEP 8: "Comments that contradict the code are worse than no comments", and inline comments "are unnecessary and in fact distracting if they state the obvious" (its example: x = x + 1 # Increment x). Google's review guide asks for comments that "mostly explain why instead of what" (What to look for).
Says why (a leaked database must not leak keys) and what the code relies on (the primary key constraint), which no name can say.
Repeats the code. When the code changes, these are the comments that go stale and start to lie.
Cost. Renaming in shared code touches every caller and every open pull request; in a library it is a breaking change (section 12). Splitting adds jumps for the reader and pays only when the new names carry meaning. Do not docstring every private three-line helper "for completeness": a good name is shorter and cannot go stale.
An abstraction is "a simplified view of something that omits unimportant details" (Ousterhout's modular design notes). A module is worth its interface when it hides much more than it exposes: "Deep class: small interface, lots of functionality"; a shallow one has a complex interface or little behind it, so "invoking a method isn't much easier than just typing in the code of the method". His canonical deep module is Unix file I/O: a handful of calls (open, read, write, close and a seek) hide disks, caches, permissions and whole file systems. The idea is David Parnas's information hiding ("On the Criteria To Be Used in Decomposing Systems into Modules", Communications of the ACM, 1972), which Ousterhout calls "the single most important idea in software design".
Fig. 2 measures it on the refactored service (step 10): every function drawn the way Ousterhout draws modules, counted from the file by gen_data.py. A proxy: real interfaces also include errors, side effects and ordering rules, which no line count captures.
with statement.Three warnings from the same notes, each visible in the running example:
LLMClientWrapper whose methods each call one SDK method is the everyday case: either hide something real (retries, typed errors, a smaller interface) or call the SDK directly.claim_key was fairly deep, but the handler still released the key itself, on two paths (Fig. 2, step 4).idempotency_claim, which releases the key on every exit without a saved response. The caller's interface got smaller, and a latent bug disappeared as a side effect: in steps 0 to 9, a crash after claiming a key left it "started" forever, so every retry got (measured; section 9).illustrative code written for this page in the running example's names; the sequence and the remedy are Metz's.
Every abstraction is a loan: it saves principal (duplicated code, places a change must touch) and charges interest (one more name to learn, one more jump when reading, one more shape every future change must fit). Two rules decide whether to take it.
The rule of three. "The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor." Popularised by Martin Fowler's Refactoring (1999) and attributed there to Don Roberts (1st edition, p. 58, quoted on the c2 wiki; also Wikipedia; the book is not online, so this is a secondary quotation). With two copies you cannot yet see which parts really vary; with three, the axis of variation is visible, so the abstraction is shaped by facts rather than guesses. The demo service's auth check appeared four times (one per endpoint), which is why step 8 of the refactor turns it into one dependency.
The wrong abstraction costs more than duplication. Sandi Metz: "duplication is far cheaper than the wrong abstraction" (The Wrong Abstraction, 2016; she notes the phrase circulated earlier). Step through how it happens and her remedy (green lines are new at each step):
Her remedy, in her words: "Re-introduce duplication by inlining the abstracted code back into every caller", keep in each copy only the branch that caller uses, delete the rest, then look again for the real shared part. "When dealing with the wrong abstraction, the fastest way forward is back."
Cheap reversibility beats prediction: prefer abstractions you can inline away (a function, a Protocol) over ones you cannot (a service boundary, a published API, a database schema), and decide those last, when you know most. When not to abstract: two copies that may diverge; a "generic" layer with one implementation and no test fake; a base class whose subclasses override most of it; a wrapper whose methods each call one method of the thing it wraps (shallow: it adds a name and hides nothing).
Protocol), and discovery through entry points, a standard packaging mechanism "for an installed distribution to advertise components it provides" (spec). pytest finds plugins through the pytest11 entry point and its pluggy core "enables 1400+ plugins"; Airflow providers declare an apache_airflow_provider entry point; vLLM loads general plugins from the vllm.general_plugins group. Cost: a plugin interface is forever (Hyrum's law, quoted on Building a backend API), so start private and promote to a plugin API only under demonstrated demand.The demo service is one 200-line file, and at that size one file is right. Picture it at 5,000 lines with a second way in (a nightly batch job that summarises chats) and a second database (Postgres in production, SQLite in tests). Now "where does this code go?" decides how much has to change when one of those outside things changes. The organising idea is ports and adapters (hexagonal architecture), from Alistair Cockburn's 2005 article: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." The product's rules sit in the middle and know nothing about HTTP, SQL or a vendor's SDK; a port is an interface the middle defines ("something that can give me a chat's messages"), an adapter implements it for one technology (Postgres, SQLite, an HTTP client, a fake for tests).
Fig. 3 lays that service out as terraces, the rules on top (the names are illustrative; the structure is the one this section describes):
domain/ holds the pure rules (fingerprints, prices, reply parsing) and ports.py the interfaces they need. It imports nothing from the project and knows nothing about HTTP, SQL or a vendor's SDK.api/ (the FastAPI routers) imports services/ (the use cases), which import domain/ and the ports. The arrows are imports, and they all climb toward the stable rules.ChatStore and ChatModel are Protocols in ports.py (glass plates at the core's edge). postgres_store.py and http_model.py implement them (dashed) without the core knowing they exist.api/, the use case calls the ChatStore port, and the call leaves through the Postgres adapter to the database (and through ChatModel to the model API). Control goes outward while every import points inward: that inversion is the whole trick.os.environ or opens connections.FakeModel, a FakeStore, a scripted HTTP transport): 11 passed in 0.06s.Dependency direction is the rule that matters (steps 1 and 2): nothing imports api or adapters except main.py. The rule can be enforced in CI with import-linter (2.15, September 2026), whose "layers" contract fails the build when a lower layer imports a higher one. Where I/O lives: I/O is anything that leaves the process (network, disk, database, clock, randomness, environment variables). It is slow, can fail, and makes tests need setup, so push it to the edges: read what you need, decide in plain functions, then write the results (section 7 measures why).
A Protocol (PEP 544, Python 3.8, "static duck typing") declares the methods something must have; any class with matching methods satisfies it, with no base class and no import of the protocol. Prefer it to an abstract base class when the implementations live in other packages or in tests. (How the type checker treats it is Python: typing, uv, packaging and the toolchain, section 1's.)
Dependency injection in Python is one habit: a function or class receives the things it uses instead of creating them. The tangled LLM call created its own database connection (sqlite3.connect(os.environ["CHAT_DB"])) and called a module-level httpx.post, so testing it means patching globals. The refactored one takes them as arguments:
The unit test for the retry policy passes sleep=slept.append and an httpx client with a scripted transport; it checks that a 429 then a 503 are retried with waits of exactly 1 and 2 seconds, in milliseconds, without sleeping or touching a network (test_http_model_retries_only_transient_errors in src/llmcall/test_after.py). One place, the composition root (usually main.py), builds the database pool, the HTTP client and the settings once at start-up and passes them down; nothing else calls os.environ or opens connections. FastAPI already has injection: Depends(current_owner) in step 8 of the refactor is it, and tests swap a dependency with app.dependency_overrides. Pass fakes (small working implementations, such as an in-memory store) rather than mocks (objects that record calls and return canned values): the Review lab has a real test that still passes when the function it claims to test is broken (Testing and quality section 4 owns test doubles). Cost: parameters multiply, so give the common case a default (sleep=time.sleep); do not inject what never varies (the json module, pure helpers); a DI container library is rarely worth it in Python.
Cost. Every layer is a file to open and a name to learn. For a CRUD service whose "rules" are "store what the client sent", a service layer that only forwards calls to a repository is a shallow module: pure cost. Start with one module per feature (chats.py, billing.py); introduce a port when a second adapter actually appears (a test fake counts) or the rules grow beyond a screen.
A dataclass (standard library) generates __init__, __eq__ and __repr__ and checks nothing at run time; attrs does the same with more options. A pydantic BaseModel validates and converts every value when the object is built, raising an error that says which field and why. Validation is the point at an input boundary and wasted work everywhere else:
Nothing for one request, real money in a loop over ten million log rows. So: pydantic at the boundaries (HTTP bodies, LLM outputs, config read from the environment with pydantic-settings 2.15.0, files from outside), dataclasses or attrs inside.
Two surprises: model_construct, the documented "skip validation" escape hatch, is slower here than validating (pydantic's performance notes and model docs warn that in V2 "for simple models, going with validation may even be faster"), and parsing JSON straight into a model (model_validate_json) beats json.loads plus a dataclass, which is why pydantic's docs say to prefer it. Two signature habits from the old page: accept abstract types, return concrete ones (take Sequence[Message] or Iterable; return list[Message]), and avoid "stringly typed" values (a str that is really one of five model names should be a Literal or an Enum).
real best of 7 runs of 100,000 constructions, nanoseconds per object, on an , Python , pydantic (pydantic-core ), attrs ; script src/bench/bench_models.py. Absolute numbers depend on the machine; the ratios are the point.
The Gang of Four's Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994) states the principle in five words: "Favor object composition over class inheritance" (chapter 1; the book is not online). Inheritance reuses code by making a class a kind of another class, so the subclass depends on its parent's insides (tight coupling, and the coupling cannot be changed at run time). Composition reuses code by holding another object behind its interface, so each piece can be swapped or stacked. The difference shows the moment features combine:
Predict: two model providers, and you want retries, caching and logging in any combination. How many classes does each design need? Then press the feature buttons on the right.
Inheritance is still right for a true "is a" with a stable parent you control: an exception hierarchy (section 8), a framework's base class that is designed for it. Python's mechanics (the MRO, mixins, super()) are Python: the data model and protocols, section 5's.
Derived, illustrative names: with m providers and k optional features, a subclass per combination needs m × 2k classes (2 × 8 = 16 at three features, counting the plain one); wrappers that each satisfy the same ChatModel Protocol need m + k = 5 and are stacked at the composition root: Logged(Cached(Retrying(HttpChatModel(...)))). Each wrapper is testable alone with a fake inside it.
A design pattern is a named, reusable shape for a recurring problem. It helps when the variation it handles already exists in your code (the third copy of section 4) and when the name speeds review ("this is a Strategy"). It hurts when applied before the variation exists, which adds the interest of an abstraction without the principal. Many classic patterns shrink in a language with first-class functions and modules: Peter Norvig found "16 of 23 patterns have qualitatively simpler implementation in Lisp or Dylan than in C++ for at least some uses of each pattern", for example Strategy, Command, Template Method and Visitor through first-class functions and Facade through modules (Design Patterns in Dynamic Languages, first presented 5 May 1996). Python has the same features:
| Pattern | The Python form | Here |
|---|---|---|
| Strategy | pass a function (or an object satisfying a Protocol) | sleep=time.sleep in HttpChatModel |
| Adapter | a class that implements a port for one technology | SqliteChatStore, HttpChatModel |
| Decorator (the GoF one) | a wrapper satisfying the same Protocol | Retrying(HttpChatModel(...)) above |
| Factory | a function, or the class itself (classes are callables) | the composition root |
| Singleton | a module-level object, or better one built in main.py and injected; a singleton reached from everywhere is a hidden global (coupling) | the HTTP client and database pool |
| Observer | a list of callbacks | |
| Facade | a module whose __all__ is the public surface | chatsummary/__init__.py (section 12) |
When patterns hurt: an AbstractFactory with one product, a Visitor over a three-case union that a match statement says in six lines, a class with one method that should have been a function.
A pure function returns a value computed only from its arguments and changes nothing outside itself; it is trivial to test (call, compare) and safe to reuse. Functional core, imperative shell is Gary Bernhardt's name for putting the decisions in pure functions (the core) and the I/O in a thin outer layer (the shell) .
The example: a function that gives a chat a title and a summary by calling an LLM. "Before" is the shape such code reaches after a few months of fixes: one function reads the database, builds the prompt, calls an OpenAI-style HTTP endpoint with retries, digs JSON out of the reply and writes the result. "After" does the same job as a core, two ports, two adapters and a six-line shell. Both were written for this page and run through the same seven situations with a scripted fake server (no network), counting HTTP calls and seconds spent sleeping between retries. Fig. 4 shows both, sized by the real files:
before.py's summarize(): 42 lines, McCabe complexity 14, every step of the job above inside one except Exception.render_transcript (2 lines) and parse_summary (7 lines) sit on the glass plate: pure. summarize_chat (6 lines) is the shell. ChatStore and ChatModel are ports (Protocols, no body); SqliteChatStore (6 lines) and HttpChatModel (18 lines) are the only code that touches the disk or the network. Heights are lines of each body; cc is radon's complexity.ChatStore port for the chat's messages; SqliteChatStore runs the query.render_transcript, which returns the prompt text. No I/O, so its test is a call and a comparison.ChatModel port; HttpChatModel posts it and retries only what retrying can fix (429, 5xx, dropped connections), waiting 1 s then 2 s.parse_summary, which returns a validated Summary or raises; the shell saves it through ChatStore.save_summary.before.py makes 3 calls, sleeps 7 s and returns None; after.py makes 1 call, and parse_summary raises ModelOutputError saying what came back.The seven situations, side by side (pick one on the right):
In four of the seven situations "before" returns None, and in two of those only after three calls and seven seconds of sleeping, so a caller cannot tell "the model refused" from "our request is malformed" from "this chat is empty". The cause is one line: except Exception around everything, which turns every bug, including a KeyError in our own parsing and a 400 that says our request is wrong, into "retry and hope". "After" retries only what retrying can fix (429 and 5xx responses, dropped connections) and says what went wrong with a typed exception.
The core (render_transcript, parse_summary) is where the bugs were, and it now has unit tests that need no server, no database and no mocking library: for 11 tests. The shell (summarize_chat) is two lines of logic, so a handful of tests with fakes cover it.
Cost. "After" is longer ( source lines against ) and has eleven functions instead of one. For a one-off script you run by hand that is overhead: keep it tangled and short. It pays as soon as the code runs unattended, has more than one caller, or needs tests. One honest behaviour change: "before" silently cut titles to 200 characters, "after" rejects them as a model output error. That was a decision, and it belongs in the pull request description, not hidden in a refactor.
real both files run on with httpx and pydantic ; script src/llmcall/measure.py. Retry sleeps are recorded, not slept.
Returning None for four different failures is the commonest error-handling mistake in Python services: the reason is thrown away, and the logs say summarize failed: 'choices' from inside a retry loop. PEP 20: "Errors should never pass silently. Unless explicitly silenced." Python's idiom is to raise an exception that travels up until a caller that can act catches it, in the style the glossary calls EAFP, "Easier to ask for forgiveness than permission" (glossary). The mechanics (chaining, groups, finally) are Python: the data model and protocols, section 6's; the design is four rules:
SummarizeError.ChatNotFound (show a 404), ModelOutputError (log, maybe try another prompt), ModelUnavailable (retry later).retryable = True), so retry code does not parse messages.raise ModelOutputError(str(e)) from e chains the original, so the traceback shows both.Where to catch: where you can do something (retry, fall back, or turn the error into a response). In the refactored service that is one place: a single exception handler turns every ProblemError into an RFC 9457 problem response (step 2 of the refactor; the HTTP side is section 2 of Service APIs). Everywhere else, let exceptions travel. Catching just to log and re-raise doubles every log line; catching Exception "to be safe" is the bug measured in section 7 (ruff flags it as BLE001, blind except).
Define errors out of existence (Ousterhout, exceptions notes: "Whenever possible, define errors out of existence"): choose semantics where the awkward case is not an error. set.discard(x) does nothing if x is absent (set.remove raises), os.makedirs(path, exist_ok=True), dict.get(key, default); in the refactor, idempotency_claim releasing the key on every exit removes a whole category of "forgot to release" errors.
Cost. A hierarchy is interface: every class you publish is a promise (section 12). Do not create one exception class per function. Exceptions are slow-ish in tight loops and wrong for expected outcomes ("no more pages" is a return value, not an error).
The old page described the retry pattern correctly. Two things changed since: the SDK is now at major version 3, and its README says its clients are "powered by HTTPX2" (pydantic's fork of httpx), whose exception tree mirrors httpx's (httpx: HTTPError splits into RequestError, with TransportError and its timeouts below it, and HTTPStatusError; docs). Code that caught httpx.TimeoutException around SDK calls should catch the SDK's own APITimeoutError instead: depend on the interface the library publishes, not on what it happens to use inside.
The OpenAI Python SDK at v3.24.0 (_exceptions.py). Its README: "Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default", 2 times with a short exponential backoff, and "Requests are retried only when their body can be safely resent". after.py copies the policy at small scale: only TransportError, 429 and 5xx are retried. Retry policy as a whole (backoff, jitter, budgets) is Reliability engineering's.
real 14 characterization tests written first (one more joins at step 10); after every step src/refactor/run_steps.py ran them and measured, on (pytest , radon , ruff with rules ). "Complexity" is McCabe cyclomatic complexity of the handler, computed by radon.
Martin Fowler's definition: a refactoring is "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior". If behaviour changes, it is not a refactoring and belongs in a separate, reviewed change. His book Refactoring (1999; 2nd edition 2018, examples in JavaScript) is a catalogue of small, named, safe moves: Extract Function, Inline Function, Rename Variable, and dozens more. For code with no tests, Michael Feathers (Working Effectively with Legacy Code, 2004) named the first tool: a characterization test, whose purpose "is to document your system's actual behavior, not check for the behavior you wish your system had" (Feathers, 2016): call the code, record what it does today, even if it looks wrong, and assert exactly that. His blunt definition from 2002: "The main thing that distinguishes legacy code from non-legacy code is tests, or rather a lack of tests." Then the loop: one small change, run the tests, commit; when a test goes red you know exactly which change did it, and undoing it costs seconds. Kent Beck: "for each desired change, make the change easy (warning: this may be hard), then make the easy change" (2012, quoted by Fowler).
Predict: ten small steps, or one rewrite to the same design. Which keeps all 14 characterization tests green, and which ends with the lower complexity score?
Press the modes on the right; each step below is one commit, tested and measured.
send_message from the backend API page's demo service: 52 lines doing authentication, rate limiting, idempotency, storage and the model call inline, complexity 9. Ruff's PLR0911 (too many return statements, default limit 6) fires on it.ProblemError exception and one handler that turns it into an RFC 9457 response. The handler raises instead of building responses, so a helper can fail without returning a special value, and PLR0911 stops firing once errors are raised instead of returned.make_reply); writing it is I/O (save_reply: one transaction); the handler only wires them together. Steps 1 to 7 change structure only, and the tests prove it: 14 of 14 green every time. Complexity falls from 9 to 6 and the handler from 52 to 28 lines.MessageService class, written without running the old tests until the end, the handler shrinks to 10 lines with complexity 2, and 4 of 14 tests fail: the fingerprint forgot the chat id, the key is no longer released after a 404, and replays lost their Idempotent-Replayed header. A fifth change no test covers: streaming to a chat that does not exist now returns instead of . The rewrite was written for this page and its bugs are planted, but they are the kind a rewrite makes: details that lived in the old code's structure and in nobody's head.Cost. Characterization tests first are real work (here, 14 tests for one handler), and refactoring takes review time that ships no feature. Do not refactor code that is about to be deleted, code nobody needs to change, or during an incident. Never mix a refactoring and a behaviour change in one pull request: the reviewer cannot tell which line is which.
McCabe's cyclomatic complexity counts independent paths through a function (roughly, 1 plus the number of decision points). His 1976 paper proposed 10 as "a reasonable, but not magical, upper limit" (McCabe, IEEE TSE, 1976, scanned copy); ruff's C901 uses 10 by default and radon grades 1 to 5 as A and 6 to 10 as B (radon docs). The original handler scored 9, under every threshold, and was still the hardest function in the service to change. Metrics find candidates; they do not judge design. The rewrite's score of 2 is the proof: the lowest number on the chart belongs to the broken version.
A coding agent edits, runs something, reads the result and edits again. It stops when the work looks done, so the design question is what it can check and how much it must read. Anthropic's Claude Code guidance puts both constraints plainly: "Give Claude a check it can run: tests, a build, a screenshot to compare", and "Claude's context window fills up fast, and performance degrades as it fills" (Best practices for Claude Code, page updated 2026-10-20, read 2026-10-24). Everything in sections 1 to 9 serves an agent for the same reasons it serves a human, with less slack:
idempotency_claim is cheaper to load than 52 interleaved lines.pip install of an unknown suggested package can install malware.Plausible is the risk: the failure mode is code that looks right, passes the tests it wrote for itself, and is subtly wrong at the edges. Reviewing what comes back is the same review as for a human, with a higher bar ("LLM-authored code raises the review bar, not lowers it", from the old page): read the tests first (do they test behaviour, or mocks?), then the edges assistants handle worst (error paths, retries, empty inputs, concurrency, time zones). The "retry everything" and "blocking call in async code" diffs in the Review lab are both typical. Where tests are silent on very large or AI-written changes is Testing and quality's section 13; the harnesses that run agents are Topic: agentic-harnesses; how coding agents are benchmarked, and why scores can mislead, is Agentic benchmarks and the paper page Schrödinger's Code Repository (has an LLM learned SWE-bench or memorised it?).
Static diagram. Evidence from this page's own runs: the characterization tests caught step 8's 401 against 422 (section 9); mypy --strict found 1 error in the unannotated tangled call and so would not guard it (depth block "Types"); ruff's BLE001 flags the blind except Exception of section 7. Where no check exists, "looks done" is the only signal, and the reviewer becomes the loop.
Ward Cunningham coined the metaphor in his OOPSLA 1992 experience report: "Shipping first time code is like going into debt. A little debt speeds development so long as it is paid back promptly with a rewrite", and "Every minute spent on not-quite-right code counts as interest on that debt" (The WyCash Portfolio Management System). The useful part is the decision it frames: debt is fine when it buys something and its interest is small; it is a problem when nobody chose it or nobody pays it down.
Martin Fowler's Technical Debt Quadrant (14 October 2009): "the useful distinction isn't between debt or non-debt, but between prudent and reckless debt", and "there's also a difference between deliberate and inadvertent debt". The cell texts paraphrase his examples. Prudent and inadvertent debt is, in his words, "not just common but inevitable for teams that are excellent designers": you learn what the design should have been by building it.
A library is code whose callers you do not control: another team, the open-source world, or you in another repository. Every rule above gets stricter, because you cannot fix the callers when you change something. The bar the old page set: a colleague can use the package correctly from the type signatures alone. To make it concrete, the refactored LLM call was packaged as a real library, chatsummary 0.3.0 (in src/libdemo/), and built.
PEP 8: "Any backwards compatibility guarantees apply only to public interfaces", and modules "should explicitly declare the names in their public API using the __all__ attribute". The reason to be strict is Hyrum's law (quoted on Building a backend API): with enough users, every observable behaviour will be depended on by somebody, documented or not, so the smaller the surface, the less you are stuck with.
summarize_chat); everything else supports it.* in the signature (PEP 3102) forces summarize_chat("c1", store=s, model=m): call sites say what each argument is, and you can add or reorder options later without breaking anyone.summarize(chat, True) means nothing at the call site; summarize(chat, force=True) does, and two behaviours behind one flag are often two functions.mypy --strict on it: "".Semantic Versioning 2.0.0: given MAJOR.MINOR.PATCH, increment MAJOR "when you make incompatible API changes", MINOR "when you add functionality in a backward compatible manner", PATCH "when you make backward compatible bug fixes"; and "Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable." That is why users pin 0.x libraries tightly (pydantic>=2.7,<3 pins a major; for a 0.x dependency pin the minor). For HTTP APIs the same judgement (which change breaks a client) is section 2 of Service APIs.
DeprecationWarning one minor version before removal". Python's own policy, PEP 387, asks for more: "Wait for the warning to appear in at least two minor Python versions of the same major version", and "It is preferred, though, to wait 5 years before removal". That is CPython's rule, not a law for every library, but "at least two releases" is the safer default. Two facts the old page missed: PEP 565 makes DeprecationWarning visible by default only for code running directly in __main__, so your users' applications usually do not show it; their test runs do, since pytest displays it by default (pytest docs). For warnings meant for end users of an application, the warnings docs point to FutureWarning.Cost. A published library turns every refactor into a compatibility question. Inside one monorepo, an internal module whose callers can all be changed in one commit needs no semver or deprecation shims: change the callers. Promote code to a library only when callers live in places you cannot edit.
Everything about a package lives in pyproject.toml: its metadata (PEP 621), the build backend that turns source into a wheel (PEP 517 and 518) and tool settings. The real file used to build chatsummary:
A wheel is the built, installable archive (). In 2026 most teams create and manage projects with uv (0.12.23, 2026-10-03): uv init --lib, uv add pydantic, uv build, uv publish. The src/ layout (code under src/chatsummary/) prevents tests from accidentally importing the source folder instead of the installed package. Wheels, tags, ABIs and trusted publishing are taught in Python: typing, uv, packaging and the toolchain, section 7.
real called with the old name it still works and emits "", pointing at the caller's line () thanks to stacklevel=2. Without the shim, the same call fails outright: (from the Review lab).
A code review is a second engineer reading a change before it merges (Google's guide says CL, for changelist; GitHub says pull request). It catches bugs, but its bigger jobs are spreading knowledge and keeping the codebase consistent. The best free reference is Google's published guide, Google Engineering Practices. Its standard: "In general, reviewers should favor approving a CL once it is in a state where it definitely improves the overall code health of the system being worked on, even if the CL isn't perfect" (The Standard of Code Review). Holding out for perfection teaches authors to batch changes into huge PRs that are even harder to review.
Spend attention in this order (from the old page, consistent with Google's What to look for: design, functionality, complexity, tests, naming, comments, style, consistency, documentation, every line, context, and good things):
Writing a comment. Label the weight: "If it's not very important, prefix it with something like "Nit: "" (comments guide); the Review lab uses blocking question nit praise. About the code, never the developer, and explain why: "this retries 400s, which are our bugs, three times" teaches; "wrong" does not. Ask when the author has more context ("what happens if the chat is deleted mid-stream?"). Say what is good: "good things" is on Google's list because it tells the author what to keep doing.
Size and speed. "100 lines is usually a reasonable size for a CL, and 1000 lines is usually too large, but it's up to the judgment of your reviewer" (Small CLs); "One business day is the maximum time it should take to respond to a code review request" (Speed): to respond, not necessarily to finish. Review is a queue: a change waiting a day is a day of latency for every change behind it, which is the reason behind both numbers.
Practise on the Review lab: eleven real diffs to this page's code, each flagged problem demonstrated by running it. This page owns review and static checks as craft; running them as CI gates (which check runs first, what blocks a merge) is Testing and quality's section 12.
Google's author guide (handling comments): "Don't Take it Personally", and "If a reviewer says that they don't understand something in your code, your first response should be to clarify the code itself": a reply helps one reader once, a clearer name helps every reader after. Write the PR description for a reviewer with no context (what changed, why, how it was tested, what you are unsure about), and split refactorings from behaviour changes so each PR answers one question.
Closed blocks. The language mechanics of typing and the toolchain are Python: typing, uv, packaging and the toolchain's (sections 1 to 5); what stays here is what they mean for design, with the versions as of 2026-10-04.
Python does not check types when it runs: def f(x: int) happily accepts a string. A type hint (PEP 484, written 2014, Python 3.5) is an annotation for tools; a type checker reads the hints without running the code and reports calls that cannot work (passing None where a str is required, forgetting that a lookup can fail, misspelling an attribute): a whole class of bugs found in seconds at your desk, plus documentation that cannot go stale because CI checks it.
Read them as sentences: JSONResponse | None ("a response, or nothing"; the | spelling is PEP 604, Python 3.10) forces every caller to handle the nothing; Literal[...] limits a string to known values, so a typo like "asistant" is caught; the bare * makes everything after it keyword-only.
Four checkers exist: mypy (2.4.0, the reference), pyright (Microsoft, inside VS Code's Pylance), ty (Astral, a 0.0.x beta) and pyrefly (Meta); their versions, strict settings and how they disagree on the same code are in Python: typing, uv, packaging and the toolchain, section 2.
What pros do: pick one checker, run it in CI and in the editor, and make new code pass its strict mode while old code is brought in module by module. Two checkers disagreeing on edge cases is normal; running two is rarely worth it.
before.py), mypy --strict reports error: "". Not one of its real problems. Without annotations every parameter is Any, and Any is compatible with everything, so there is almost nothing to contradict. Type checking pays only once the signatures carry types. after.py, fully annotated: errors under the same flags, and now a wrong call would be caught.Overloads, when the return type depends on an argument. The official OpenAI SDK (v3.24.0, 2026-10-02) types chat.completions.create with @overload: with stream: Literal[True] it returns Stream[ChatCompletionChunk], otherwise a ChatCompletion (source at the tag), so iterating over a non-streamed reply is an error at your desk. Also: NewType("ModelId", str) so a model id cannot be passed where a chat id is expected, and generic functions with PEP 695's def first[T](xs: Sequence[T]) -> T (Python 3.12).
Cost. Annotations take time to write, and the checker has opinions about dynamic code (decorators, **kwargs plumbing, ORMs) that can take an hour to satisfy. # type: ignore[code] with the specific code is the honest escape. Do not chase strict mode in a throwaway notebook.
| Job | Tool (PyPI version, release date) | What it does for you |
|---|---|---|
| Lint and format | ruff 0.16.10, 2026-10-01 | One tool for hundreds of lint rules (pyflakes, pycodestyle, isort, bugbear, pylint subsets) and a formatter; its docs claim "10-100x faster than existing linters (like Flake8) and formatters (like Black)". The formatter is "designed as a drop-in replacement for Black": on Django and Zulip "> 99.9% of lines are formatted identically" (docs). Black itself (26.10.0, released 2026-10-04) is still maintained. |
| Type check | mypy 2.4.0 or pyright 1.1.414 (ty, pyrefly newer) | The block above. |
| Run checks before each commit | pre-commit 4.6.2, 2026-08-10 | Runs the hooks listed in .pre-commit-config.yaml on the files you changed, at git commit, so formatting never reaches review. |
| Projects, dependencies, Python versions | uv 0.12.23, 2026-10-03 | Creates projects, resolves and locks dependencies (uv.lock), installs Python itself, builds and publishes. |
| Tests | pytest 9.1.1; hypothesis 6.168.3 | Owned by Testing and quality, which also covers CI. |
The real configuration that built chatsummary, plus the pre-commit file that would run it (the ruff hook block is the one from ruff-pre-commit's README; tags checked 2026-10-04):
Rule selection is a decision, not a default: ruff enables only a small default set, and C901 (complexity) is not in it. What a few chosen rules found on the tangled LLM call, for real:
Cost. Every rule you enable is a rule someone must satisfy or silence. Turning on everything (select = ["ALL"]) on an old codebase produces thousands of findings and teaches people to ignore the linter. Start with the defaults plus a few rules that catch bugs (bugbear B, blind except BLE), add more one at a time, and fix or baseline existing violations when you do.
Eleven pull requests against the code on this page: the chat API handler, the refactored LLM call (after.py) and its tests. Read the diff, decide what you would comment and whether you would approve, then reveal a reviewer's comments. Every flagged problem that can be demonstrated was demonstrated: the diff was applied to the real code and run (src/review/proofs.py, proofs2.py), and the result is shown under the comments. The diffs were written for this page; the patterns are the ones that reach real reviews, several of them typical of AI-written code.
Try: do all eleven without revealing, writing your comments down; then compare. Labels: blocking must change before merge, question the author may know something you do not, nit polish the author may ignore, praise keep doing this.
Times are estimates for a careful first read. Links checked 2026-10-04; links added 2026-10-24.
Eleven pull requests against this page's code: comment, decide, then compare with a reviewer and the run evidence. About 25 min.
The root: one request to an LLM chat product followed from 1 user to 10 million. Its tabs: Scale simulator, Numbers to know, Case files (33 real outages and architectures). About 21 min.
The service whose handler is refactored here: its request lifecycle, pydantic validation at the edge, the data layer, workers and shutdown (the API contract itself, errors and versioning, is Service APIs). The other half of the old "API and Code Design" page. About 27 min.
Unit, property-based, data and model tests and CI: the tests that make refactoring safe. About 46 min.
Timeouts, retries with backoff and jitter, circuit breakers: the policy behind "retry only what retrying can fix". About 40 min.
What to log (and not to log) around LLM calls; metrics and traces. About 39 min.
The LLM gateway and model routing that the ChatModel port would sit behind. About 28 min.
Where the summarise job would run in production: a background worker. About 40 min.
Replication, partitioning and consistency. About 46 min.
Measuring before optimising; why a blocking call in async code caps throughput. About 39 min.
Whole designs, from requirements to bottlenecks. About 41 min.
Owns typing mechanics (section 1) and the toolchain: type checkers, packaging, uv, ruff, wheels. 22 min, plus 15
Owns classes and inheritance (section 5) and exceptions (section 6). 28 min, plus 21
The harnesses that run AI coding assistants.
How coding agents are measured (SWE-bench, Terminal-Bench) and what the scores mean.
Paper page: have LLMs learned SWE-bench or memorised it?
Evals as the "tests" for prompt and model changes in review.
John Ousterhout, 2nd edition 2021. Deep modules, information hiding, complexity as the enemy: the best short book on abstraction. About 4 h 45 min.
Their written debate (2024 to 2025) on method length, comments and test-driven development. About 1 h.
Martin Fowler, 2018: the catalogue of safe, named refactorings (examples in JavaScript). Read the first four chapters, then use the catalogue. About 4 h for the opening chapters.
Michael Feathers, 2016, on pinning what code does before changing it; his book Working Effectively with Legacy Code (2004) is the long version. 10 min (post).
Communications of the ACM, 1972: where information hiding comes from. About 30 min.
Martin Fowler, 2009; with Ward Cunningham's OOPSLA 1992 report where the debt metaphor starts. 10 min.
Peter Norvig, 1996: why 16 of the 23 classic patterns shrink with first-class functions and modules. About 30 min (slides).
Vendor guidance on giving an agent a check it can run and keeping its context small. About 25 min.
Reviewer and author guides; calibrates what to flag and what to let go. About 1 h.
Sandi Metz, 2016. 5 min.
Gary Bernhardt's free screencast, 2012; then his talk Boundaries. About 45 min for both.
Alistair Cockburn's ports and adapters article. 20 min.
Python's style guide, and its backwards compatibility and deprecation policy. 40 min and 10 min.
The versioning contract, with its FAQ. 10 min.
The randomised trial behind "19% slower", and the 2026 update. 20 min.
The contract layer at the boundaries: models, validators, settings, performance notes. About 1 h 30 min for the core pages.
The Python typing guides and spec: Protocols, overloads, generics. About 1 h.