Files
claude-config/principles/technical-principles.md
T

22 KiB

Purpose and goals of our principles

  1. Efficiently and sustainably deliver technical solutions with fewer bugs that are easier to resolve.
  2. Make our technical solutions easier to maintain and further develop.

Principles

  • Compose, do not entangle — the core design rule, at every level from services down to functions.
    • Two things that can stand alone stand alone, joined by a narrow seam you can name; never by one reaching through the other. The test, for any design routing A through B or having A reach into B: does A still work when B is absent, broken, half-deployed or swapped for something else? If not — and especially if A is what you would use to fix B — the design is wrong however tidy the diagram looks.
    • Services and networking: a deploy trigger, health probe, backup job or admin path gets its own way in, since one routed through the application it operates on fails in exactly the state it exists for. BANNED: a deploy webhook reached through the app's own reverse proxy. GOOD: its own listener, answering while the app is down.
    • Modules: dependencies point one way. Callers may know the service; the service never knows its callers, and neither it nor its comments name or assume the delivery mechanism (controller, HTTP, request validation, route), because a queue worker, a CLI or another service may call it too. BANNED: // The controller's validator guarantees these fields. GOOD: "callers must supply X", or the guard and the type signature alone.
    • Functions: a function takes what it needs as arguments and returns what it produces. One that works only after another has set up shared state, or leaves state for the next to find, is entangled with it. BANNED: validate(conf) that fills defaults send(conf) relies on. GOOD: send(withDefaults(conf)).
    • Tests and tooling: a test, script or pipeline stage that passes only because another ran first is entangled; it states what it needs and gets it. A shared environment is one that other tests, people or a second copy of the test use at the same time. A test on one also holds these rules:
      • Assert only on records the test created and can name, never on a count or the first row. BANNED: expect(rows.length).toBe(3); expect(rows[0].name).toBe("Ada"). GOOD: expect(rows.find((row) => row.id === created.id)).toMatchObject({ name: "Ada" }).
      • Never change state the test doesn't own. BANNED: a test that turns off a setting every tenant shares, or empties a table to start clean. GOOD: the test creates a tenant and changes the setting there.
      • Pass in any order, and beside a second copy of the test running at the same time. BANNED: a fixture user named test-user@example.com. GOOD: user-${unique}@example.com, where the test made unique for this run.
      • A helper registers its teardown before it creates anything, keyed by a value it made itself, and the teardown deletes only what it can name. BANNED: create the order, then register DELETE FROM orders WHERE created_at > :start. GOOD: make a reference, register DELETE FROM orders WHERE reference = :reference, then create the order under it.
      • A helper that saves a record checks what was saved, never the status code alone. BANNED: expect(response.status).toBe(200) as the helper's only check. GOOD: read the record back and compare each field the helper set.
    • Proximity is not a reason. Reusing a listener, config file, table, module or service because it is already there, when the new thing has no relationship to it, is how entanglement gets in. If you cannot name the seam, there is none.
  • Functional core, imperative shell — a core rule beside "Compose, do not entangle": no other principle overrides it.
    • Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own.
    • Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs.
    • BANNED: new Date(entry.msTimestamp ?? Date.now()) in a formatter; a test swapping globalThis.fetch. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together.
    • Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. An entrypoint reaching into a payload to decide what to do is the smell. BANNED: if (body.tx.source === 'notification') { /* drop, skip enqueue */ } in a route handler. GOOD: the entrypoint forwards source on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code.
  • Prefer deep modules: a small, intuitive interface in front of a lot of hidden work.
    • A caller should know what a call does and what it returns, without knowing how it does it. fs.writeFile("notes.txt", data) hides opening the file, encoding, buffering, permissions and the disk itself. Yet anyone reading that line knows the outcome: the data is written, or the call fails and says why.
    • A module hides how it works, never what it depends on: what "Functional core, imperative shell" injects stays injected.
    • A shallow module costs more to learn than it saves. BANNED: a wrapper that only renames the function it calls; a module whose callers must make three calls in an order only their memory enforces. GOOD: one call that does the whole job and handles the order itself.
    • When this pulls against "Explicit over implicit", the deep module wins, unless hiding the work makes it harder for someone new to the project to tell what the call does.
  • Make invalid states unrepresentable.
    • Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors.
    • A function's inputs too: take only inputs that cannot disagree, instead of checking that they agree. BANNED: a test helper that takes a token and a message, and checks that the message holds the token. GOOD: the helper makes the token and builds the message. When a review finds a second edge case in a check, change the signature so the input can't occur.
  • Always store timestamps as full ISO datetime in UTC.
    • Always communicate timestamps as full ISO datetime in UTC from APIs with database access.
  • Always grant explicit access to data, both read and write.
  • One owner per value; a reader can name every writer.
    • At every scale, from a variable to a table, file or volume: two components writing the same one are one component with a seam nobody declared.
    • The test: from the code in front of them, can a reader list every writer to this value, and the order those writers run in?
    • BANNED: a record passed to 24 functions, 13 of which mutate it and don't return anything. GOOD: one type owns the value, the rest call it and take a result.
    • BANNED: fill(set) then adjust(set), where swapping the two lines changes the output. GOOD: const filled = fill(); const adjusted = adjust(filled);
    • BANNED: stack and edges, two arrays a comment says must stay in step. GOOD: edges derived from stack, or one array whose element type holds both.
    • Allowed, never flag: mutation that never leaves the function that made it; a loop counter; data shared and never written; a state machine with named states and one transition function.
  • Validate data and build DTOs as early as possible.
    • For example, parse a form into a strictly typed DTO as the first thing that happens instead of passing strings down to be validated deep inside a service.
    • A cast (x as Foo) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, JSON.parse, DB row), the boundary owes a type guard validating the fields it claims; past that boundary everything is typed. as unknown as T and non-null ! are the same defect wearing a hat. BANNED: const user = body as User — one rename and it is a silent lie. GOOD: function isUser(v: unknown): v is User checking each field, then if (!isUser(body)) return { error: … }.
    • DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks.
    • Don't loosen a type when refactoring. A function that returned a concrete type keeps returning it when its implementation changes, never object, array, mixed or any; introduce a DTO or value object instead. BANNED: totals(): Totals becomes totals(): array once it reads from two sources. GOOD: totals(): Totals stays, and a new SourceTotals value object holds what each source returns.
  • Always use explicit state machines.
  • Most, if not all, code should have automated tests, and each test earns its keep.
    • A valuable test checks behaviour through the unit's interface, fails when that behaviour breaks, and still passes after a refactor that keeps that behaviour.
    • Write the test first and watch it fail on its assertion, not on an error, before implementing.
    • Take expected values from the requirement — the item, ticket, spec or a hand-worked example — never from running the code or calling its helpers. A test that records today's output locks in today's bug. BANNED: assert text.endswith(applications_text(applied)), where applications_text is the code's own helper. GOOD: the expected text written out for one small input.
    • Assert the outcome — returned values, stored state, emitted output — not how the code reached it. Use real collaborators or fakes; mock only slow, nondeterministic or external edges. BANNED: asserting which internal function ran, or scanning the source with ast or a regex. GOOD: assertEqual(saved_row, {...}) against a fake store; a fake clock.
    • Never mock a service your own team runs. Test the seam to it against its real build, in a harness that runs the real stack; mock only a third party that can't be run locally in a reasonable way. The rule binds the test that covers the seam: a unit test of the caller's own logic may still use a fake, as "Use real collaborators or fakes" above allows. BANNED: the only test of the call to the team's billing service stubs its HTTP responses. GOOD: that test calls the billing service's own image, started in the test stack.
    • Pin wording only where the wording is the contract: a message a consumer parses, a published format. For prompts, help and error text, assert the facts the text must carry — an item ID, a model argument, an error code — not the sentence. BANNED: assertIn("<a 600-character prompt sentence>", prompt). GOOD: assertIn("model opus, effort high", prompt).
    • One behaviour per test, named for it, tested once, at the lowest level that reproduces it. No loops or branches in a test body; parametrize the cases.
    • A test doesn't decide at run time whether to check anything: no conditional skip, early return, or catch around its assertions. A test that needs a state creates it, or fails and names what is missing. BANNED: test.skip(created.every((count) => count === 0)) after the payroll run under test, since a broken payroll also creates zero rows. GOOD: before running the payroll, check each precondition and fail naming the one that is missing; after it, expect(created).toEqual([1, 2, 1]).
    • Every escaped bug becomes a test that fails without its fix.
    • Write no test that no real bug could fail: a constant's value, a list's length, the framework's own behaviour.
    • A test neither sleeps nor asserts on the wall clock, and seeds any randomness.
    • For pure logic over many inputs, prefer a property test: a round trip, an invariant.
    • Changing tests and changing other code are two separate processes — be very careful about doing both at once.
    • Use properly randomised UUID v7s — never aaaa-0000-style placeholders.
  • Every mutant of a changed line fails a test, unless the mutant leaves behaviour unchanged. A mutant is a small change to the code, such as a flipped comparison. One that no test notices marks behaviour the tests would let break. The stability pass checks this with a mutation run on the chunk's changed lines. Coverage is no target: it finds untested code, not weak tests.
  • Idempotent data writing.
    • Typical example: PUT /resource/{id} instead of POST /resource + Idempotent-Id header.
  • Handle errors explicitly, as values — avoid the exception path.
    • Enumerate the cases that can go wrong and return them as explicit results (e.g. a result DTO with an optional error), so failure is part of the signature instead of a hidden second channel.
    • try/catch lives only at the edges, wrapped tightly around the call that can actually throw (DB, HTTP, filesystem), converting the exception into an explicit result right there. Pure functions and core logic never throw or catch for control flow.
    • A function that both returns a result and throws for some inputs has two error channels; collapse to one. Throw only for a truly unrecoverable state.
  • Commands and Queries Separation (CQS)-ish
    • Queries must never modify data, commands may only return data that is the result of their change.
  • Copy important contextual information on buisness transactions and equal data, instead of referencing it.
    • Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table.
  • Explicit over implicit.
    • Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening.
    • Prefer explicit, descriptive names over generic ones (invoiceRowsService, not service).
  • Sane defaults, where a default serves better than an explicit ask.
    • A default earns its place where most callers want the same value, a wrong guess does no harm, and the caller can see and change it through a --help line or a documented option. Anything else is asked for.
    • Defaults live at the program's edge: a CLI, a config file, a library's public API. A library still asks for every input that can change between runs, such as data, the clock and randomness; only the code that wires a program together, such as its CLI, defaults those, as "Functional core, imperative shell" asks.
    • BANNED: a CLI that refuses to run until given --data-path and --seed, when nearly every run wants the shipped data and fresh randomness. GOOD: it uses the shipped data and fresh randomness unless a flag overrides them, and --help names those flags.
  • Deterministic order wherever order carries no meaning.
    • Sort such a list, on a key that does not move: the name a line introduces, never where it came from. Exception: id goes first. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to.
    • An import sorts on its first binding, not its path, so moving or renaming a module doesn't reorder anything. Where lines already group by kind — type imports, host packages — the key sorts within each group.
  • About seven things per level, so a reader new to the project can take in each level at once.
    • A level is what a reader looks at together: the parameters of a function and its branches (cyclomatic complexity), the methods of a class, the files in a folder and the folders beside them, the sections of a document, the components of a system, the hops of a call chain. Past about seven, group the things under names a reader can follow; each group then counts as one.
    • Parameters, branches and the values a function tracks act on each other, so a reader holds them in mind together, and a mind holds about four. Aim for four or five of them, and treat seven as the ceiling. Keep a function to one screen, about 24 lines of 80 characters.
    • Things a reader finds by name may run far past seven: 100 files named by locale, the cases of an enum, a reference list. A predictable name and a sorted order serve them better than a group would.
    • Each added level makes a reader open one more folder, file or function to find a thing, so a split must save more than it costs. Keep eight, nine or ten things in one level when splitting them would add more names, files or jumps than it removes. Say why where the level is declared: a comment, the folder's README.
    • Group by what a reader would name: a feature, a step, what changes together. BANNED: misc/, part2() or a parameter object that exists only to bring a count down. GOOD: invoices/, payments/, reports/, each holding what changes together; locales/ holding de.json to zh.json, flat.
    • Group code into files, and files into folders. A banner comment (// --- name ---) that groups a file's sections is the last resort, kept only where the language or the build cannot split the file, and the file says why it can't be split.
    • Crossing a limit asks for one of two answers, never a split at any cost: group the things, or record why they stay. Keep a limit only while the comprehension panel's readers (~/.claude/skills/comprehension-panel/) find the code it flags hard.
  • Make the entry point the first thing a newcomer finds.
    • The root holds the README and the files a tool reads only from there, such as the manifest, the lockfile and the licence, and the entry point where the ecosystem puts it there. Source, tests and tooling live in folders named by what they hold. A repo of several tools applies this to each tool's folder.
    • The entry point carries the name and the place its ecosystem expects, such as index.js at the root of an npm package or src/main.rs in a Cargo crate, with no other source file beside it.
  • Keep It Simple, Stupid (KISS): keep solutions simple, so a reader new to the project understands each part on one read.
  • Don't Repeat Yourself (DRY) is a guide, not an absolute rule. It aims at one authoritative home per piece of knowledge, one obvious way per need. Before applying it, ask whether the code would be easier to understand, easier to reason about, or easier to maintain if DRY were broken; if so, break it, so long as the spellings cannot disagree (below). A surface people write — a template, data, an API — may accept a second spelling where that makes it easier to use.
    • A value, rule, definition or concept lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner.
    • Before adding a way to do something, find the existing one and use it. The same goes for tests: extend an existing test with an assertion before writing a new one. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: token {p} renders a level that {p.first} reads a path into; name the fields you want instead. A second spelling that makes a surface people write easier to use stays (above).
    • Different needs may have different ways. A public API may offer a convenience beside the general form — a one-line call for the common case over the primitive for the rest — where each serves a caller or scenario its docs name, and the convenience is built from the primitive. Code that looks alike but encodes different knowledge is not a second spelling: merging it is the wrong abstraction.
    • Two spellings that can disagree are a correctness bug, whatever the reason for having both: derive one from the other, or reject the combination.
  • All critical flows should have good traces, from where something was initiated until it completed.
    • Use traceparent OTLP and standardized logging for this.
    • A tool that runs only on its user's own machine keeps its trace on that machine, as an archive of each run, and doesn't send anything to a collector.
  • Prefer the vendor-neutral option, and know what leaving would cost.
    • A supplier is a component like any other, so compose-not-entangle's test is the whole test.
    • Where two options do the job, the one that ties us to no supplier wins by default — dependency, protocol, format, service, provider and storage alike. Choosing neutral is usually free; it is the leaving that is expensive, so the test is what an exit costs and whether anyone has priced it.
    • Sidestep deliberately, never by drift: a capability only that vendor has, or a vendor that is the target itself (an integration we build, a format we implement). Record which of the two it is and what the tie buys.
    • Do not buy portability nobody asked for. An abstraction over one implementation, "in case we swap X", is speculative generality rather than neutrality — prefer the neutral thing, do not build a layer to preserve the option.
    • Durable records are the case with no excuse: a decision log, runbook, architecture note or schema is project documentation, living in the repository proper (docs/), plain and legible with no tool installed. A vendor's directory — .claude/, .vscode/, a CI provider's folder — holds only what that vendor executes, and points at such a record rather than holding it.
  • Semantic versioning, read strictly: a minor only adds, and a major is the only release that changes what exists.
    • "Exists" is everything a consumer can depend on, not just signatures: an added output column, a removed list value, a changed default, the facts an error names, a dropped runtime version. A consumer takes a minor without editing code, data or scripts.
    • Batch breaking changes into few majors. Before 1.0.0 the minor is the breaking unit and a patch never breaks.
  • Prefer a standalone Python script over a shell script.
    • A Python script with a #!/usr/bin/env python3 shebang runs identically across systems where shell dialects and builtins differ.
    • Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded.
  • Indent with hard tabs by default.
    • A project's own settings win: .editorconfig, linter/formatter config (Prettier, rustfmt.toml, …), or the surrounding file's existing indentation.