Skip to main content

Tech blog29 min read

Stop reinventing the wheel: where each rule belongs, and which principles earn a place

Pere PagesSoftware Engineer
A wooden workbench with a small pile of slightly different hand-made wooden wheels on one side, one finished wheel on a stand in the middle, and a staircase of five indigo and lavender drawers on the other side, each holding a different object: a stamp, a hook, an instruction card, a plug and a sheet of paper

Every new project with a coding agent tempts you to write the same rules, prompts and helper skills again from zero. This post gives a small, shared foundation instead: where each kind of rule should live (a check, a hook, a skill, a tool server or plain text), and which software design ideas, from which authors, are worth building on first.

The gist

Write each rule once, in the most automatic place that can enforce it, and build on the few design ideas that make mistakes show up fast.

  • Turn every rule a program can check into a check. A formatter, a linter, strict types, tests and continuous integration (CI, the server that tests every change) hold the rule every time. A text file the agent reads, such as AGENTS.md, is the last place for a rule, not the first.
  • Write four hooks once, for every project. A hook is a command the agent's tool runs at a fixed moment. Format after each edit, block dangerous commands, don't let the agent finish while checks fail, and show the context when a session starts.
  • Share one set of workflow skills, and write very few per project. A skill is a file of instructions the agent loads for one kind of task. Plan, build, review and release go in one shared package. A project skill comes only after you've done the task by hand three times. Write almost no MCP servers (programs that give the agent new tools): command-line tools cover most needs.
  • Start with the ideas that give fast feedback. Deep modules (a small outside that does a lot inside), types that make wrong values impossible to write, pure functions at the core, and tests through the public outside.
  • Treat SOLID and Clean Code as vocabulary, not as first rules. SOLID and Clean Code are two well-known sets of design rules. Keep the two SOLID rules that still hold, and be careful with the rest, and with very small functions everywhere.

The picture: every rule has one right place

When you work with a coding agent (an AI assistant, such as Claude Code, that reads and changes your code by itself), you write a lot of rules. "Format the code before you finish." "Never push to the main branch." "Keep the database code out of the business logic." "Use these words for these things."

Most people write these rules in a text file that the agent reads. Then the agent forgets one, so they write it again in a second file, then in a helper for one project, then in another helper for the next project. After a year, the same rule exists in five places, in five slightly different words, and none of them is enforced. That is the wheel being reinvented: the same work done again, instead of once.

The fix has two parts, and the post follows them in order:

  1. Put every rule in the right place. A rule should live in the most automatic place that can hold it. If a program can check the rule, a program should check it, every time. Only rules that need judgment belong in instructions the agent reads.
  2. Choose the rules worth having. Software design has fifty years of good ideas and many bad ones. The ones to adopt first are the ones that give fast, clear feedback, because fast feedback is exactly what lets an agent correct itself.

The first part is about tools. The second part is about ideas. Both aim at the same thing: a foundation you build once and reuse in every project.

The five places a rule can live

Before choosing a place, it helps to know what the places are. There are five, from the most automatic to the least.

  1. Automatic checks. Programs that read your code and fail when something is wrong. A formatter rewrites the layout of the code (spaces, line breaks) into one fixed style. A linter finds risky patterns, such as an unused variable or a missing await. A type checker (for example TypeScript's compiler) checks that each value is the kind the code expects (a number, a text, a list of users). Tests run the code and compare the result with what it should be. All of these usually run again in CI, the server that builds and tests every change before it can join the main code.
  2. Hooks. A hook is a small command that the agent's tool runs at a fixed moment: before the agent uses a tool, after it edits a file, when it wants to finish its turn, when a session starts. In Claude Code, hooks are set in a settings file, and a hook can block an action or send a message back to the agent (Claude Code hooks reference). The agent cannot forget a hook, because the agent doesn't run it. The tool around the agent does. (These agent hooks are different from Git hooks, which run on every commit for everyone who uses the repository.)
  3. Skills. A skill is a folder with a SKILL.md file of instructions, and sometimes scripts, for one kind of task, such as "review a change" or "write a release note". The agent reads only a short description of each skill at the start, and loads the full instructions only when a task needs them (Claude Code skills documentation). Skills are for procedures that need judgment.
  4. Tool servers (MCP). The Model Context Protocol (MCP) is a standard way to give an agent new tools that reach outside systems, such as an issue tracker, a database or a design tool (Claude Code MCP documentation). An MCP server is the program that offers those tools.
  5. Written instructions. Plain text files the agent reads at the start of every session, such as AGENTS.md or CLAUDE.md. They are the easiest place to write a rule and the weakest place to keep one: the agent reads them, but nothing forces it to follow them.

Choose the most automatic place

The five places differ in one important way: how much they depend on the agent remembering. A check runs even when the agent forgets. Written instructions work only if the agent remembers. So the choice follows one question, asked again and again: can something more automatic hold this rule?

The diagram below shows that question as a short decision path, from the most automatic place to the least.

Flowchart

The table compares the five places on the questions that matter most. A check is the only place that also protects you from your own mistakes, not only the agent's.

PlaceRuns every time, without the agent remembering?Also works for people, not only the agent?Cost to write and keep
Automatic checkYesYesLow, once
HookYesNoLow, once
SkillWhen the task loads itNoMedium, needs testing
Tool server (MCP)When the agent calls itNoHigh, it is a program to maintain
Written instructionsOnly if rememberedPeople can read themVery low

The conclusion: written instructions are the last option, not the first. A rule that sits in AGENTS.md but could be a lint rule is a rule you will explain again in every session.

A starter set of hooks

Most of the value of hooks comes from four of them. Write them once, in your user-level settings, and every project gets them.

  1. Format after every edit. After the agent writes or edits a file, run the formatter on that file. Code style then never appears in a review again.
  2. Block the dangerous actions. Before the agent runs a command, refuse the few that are hard to undo: a push to the main branch, a commit that skips the checks (--no-verify), an edit to a file that holds secrets.
  3. Don't let the agent finish while the checks fail. When the agent wants to end its turn, run the fast checks (types, lint, the related tests). If they fail, send the errors back so the agent keeps working.
  4. Give context at the start. When a session starts, print the current branch, the open task and any uncommitted changes, so the agent doesn't have to discover them.

Here is what the first and the third look like in Claude Code's settings file. The first runs Prettier, a popular formatter, on the file the agent just changed. The hook receives the details of the edit as JSON (JavaScript Object Notation) text, and jq (a small command-line tool that reads JSON) takes the file path out of it.

JSON
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write --ignore-unknown"
}
]
}
],
"Stop": [
{
"hooks": [{ "type": "command", "command": "~/.claude/hooks/checks.sh" }]
}
]
}
}

The Stop hook calls a short script. When a Stop hook exits with code 2, Claude Code doesn't let the agent stop, and shows it the error text. The stop_hook_active field tells the script that it already sent the agent back once, so the script doesn't keep it busy forever. This means the agent gets one extra try: if the checks still fail after it, the agent stops and you see the errors.

BASH
#!/usr/bin/env bash
# Runs when the agent wants to finish its turn.
# Assumes the project has "lint" and "typecheck" scripts in package.json.
input=$(cat)

# If this hook already sent the agent back once, let it stop (avoids an endless loop).
if [ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ]; then
exit 0
fi

if ! output=$( (npm run -s lint && npm run -s typecheck) 2>&1 ); then
echo "The checks failed. Fix these before you finish:" >&2
echo "$output" >&2
exit 2 # 2 = don't stop; the text above goes back to the agent
fi
Each hook turns a sentence you used to repeat ("please run the linter before you finish") into something that simply happens.

Skills: one shared set for the whole workflow, a few per project

Skills are where most of the repeated work happens, because a skill is so easy to write. The fix is to split skills into two groups.

The first group is one shared set that covers the whole workflow: plan a change, build it, review it, release it, plus a few helpers around them (file an issue, record a decision, close a session). Every project does these steps, so they belong in one versioned package that all your projects install. In Claude Code that package is a plugin, which bundles skills, hooks and settings so they can be shared (Claude Code plugins).

Flowchart

The second group is a few skills per project, only for work that exists in that project alone. A blog has a "write a post" skill. A payments service might have an "add a new payment provider" skill. If a skill would make sense in every project, it doesn't belong in one project.

Three rules keep both groups small:

  • Write a skill only after the third time. If you have done the task by hand three times, it needs judgment, and nothing in the shared set covers it, then it deserves a skill. Before that, you don't know its real shape yet.
  • If a task is always done the same way, write a script, not a skill. A skill can call the script. Judgment goes in the skill text, fixed steps go in code.
  • Put shared rules in one file that skills point to. When three skills need the same writing rules, keep the rules in one shared file and let each skill reference it. Otherwise the copies drift apart.

There is one more piece that most people skip: test your shared skills. Keep a few fixed example tasks for each important skill, and run them after every change to its text. Without them, you can't tell whether an edit made the skill better or worse.

Tool servers (MCP): write almost none

Writing your own MCP server feels like the most serious kind of work, so it is tempting. Most of the time it isn't needed.

A coding agent can already run command-line tools. The GitHub command-line tool (gh), git, npm and your project's own scripts give it issues, pull requests, packages and builds, with nothing new to maintain. An MCP server is a program: it needs updates, error handling and security reviews.

Write one only in two cases:

  • The outside system has no usable command-line tool, and the agent needs it often, with a login and some state (for example an internal service of your company).
  • Tools other than your coding agent need the same access, such as a chat assistant in the browser, which can't run commands on your computer.

Turn design rules into tests

One kind of rule is often left in text even though a program can check it: rules about the shape of the code. "The domain code (the code for the business rules) must not import the database." "The user interface must not call the payment service directly." These are design rules, and they can be tests too.

Neal Ford and his co-authors call such a test a fitness function: an automatic check that a design property still holds (Building Evolutionary Architectures). In a JavaScript or TypeScript project, a tool such as dependency-cruiser reads the imports between files and fails when one breaks a rule you wrote:

JS
// .dependency-cruiser.cjs
module.exports = {
forbidden: [
{
name: 'domain-stays-pure',
severity: 'error',
comment: 'The domain code must not import the database or the web layer.',
from: { path: '^src/domain' },
to: { path: '^src/(db|web)' },
},
],
};

Once that rule runs in CI, nobody has to remember it, and neither does the agent. This raises the obvious next question: which design rules are worth writing down at all? That is the second half of this post.

How to judge a principle: does it give fast feedback?

There are many principles, many books and many authors. A useful way to rank them is to ask one question: does this principle help a mistake show up quickly, close to where it was made?

That question matters even more with an agent. An agent is good at fixing a problem it can see: a failing test, a type error, a lint message. It is bad at problems nothing reports, such as a file that slowly grows to do five jobs. So the principles that turn mistakes into fast, visible errors move to the top of the list. The principles that depend on taste move down.

The earlier post on seven code principles you can actually check describes what good code should be and how to check each quality. This post looks at the same question from the other side: which well-known ideas, and which authors, to build on first.

The first tier: eight ideas that give most of the benefit

These eight ideas give most of the benefit. Each one comes with what it means, who wrote it down and why it helps an agent.

1. Deep modules. A module is any unit of code with an inside and an outside: a function, a file, a package. A deep module has a small, simple outside (few functions, few options) and does a lot of work inside. A shallow module is the opposite: a large outside that does little. John Ousterhout made this the centre of A Philosophy of Software Design (the book). It builds on David Parnas's 1972 idea of information hiding: each module hides one decision, so the rest of the code doesn't depend on it (Information hiding). For an agent, a deep module means less to read and fewer places to break. It can use the module from its outside without loading the inside into its limited memory.

2. Make wrong states impossible to write. Design your data types so that a value that makes no sense can't even be written. Yaron Minsky's phrase is "make illegal states unrepresentable" (Effective ML Revisited). A related idea from Alexis King is "parse, don't validate": check raw input once at the edge of the program and turn it into a precise type, instead of checking the same thing again everywhere (Parse, don't validate). Here is a payment in TypeScript, before and after:

TS
// Before: any mix of fields is allowed, even impossible ones
// (a failed payment with a paidAt date, a paid one with an error).
type PaymentLoose = { status: string; paidAt?: Date; error?: string };

// After: each state has exactly the fields it can have.
type Payment =
| { status: 'pending' }
| { status: 'paid'; paidAt: Date }
| { status: 'failed'; error: string };

With the second type, the type checker refuses a paid payment without a date. The mistake shows up while the agent is still typing, which is the fastest feedback there is.

3. Functional core, imperative shell. Split the code in two. The core is made of pure functions: the same input always gives the same output, and they change nothing outside themselves (no database, no network, no clock). The shell is a thin outer layer that reads input, calls the core and writes the result. Gary Bernhardt named the pattern (Functional Core, Imperative Shell) and explained it in his talk Boundaries. The core is easy to test, because a test only gives input and compares output.

TS
import type { Db } from './db';

// Core: pure. Same input, same output, nothing else happens.
export function applyDiscount(total: number, code: string): number {
return code === 'WELCOME10' ? Math.round(total * 90) / 100 : total;
}

// Shell: reads, calls the core, writes.
export async function checkout(orderId: string, db: Db): Promise<void> {
const order = await db.orders.find(orderId);
const total = applyDiscount(order.total, order.code);
await db.orders.update(orderId, { total });
}

This is also the honest answer to "functional or declarative?" Declarative code says what result you want instead of each step to get there, and pure functions push you towards it. Use that style in the core. In the shell, where the program talks to the world, plain step-by-step code is fine.

4. Test behaviour through the public outside. A good test calls a module the way real code calls it, and checks the result. It doesn't check how the module works inside. Such tests survive when you rewrite the inside, so they stop mistakes without stopping changes. Kent Beck's test-driven development (TDD), where you write the test before the code, pushes you towards such tests: a test written first can only use the outside, because the inside doesn't exist yet. Kent C. Dodds's "testing trophy" adds a useful balance: put most of the effort into tests that check a few units working together, because they are closest to how the software is used (The Testing Trophy). Deep modules make this easy, because their small outside is the natural place to test.

5. Let tools settle style. Use a formatter, so nobody discusses spaces again (Why Prettier?). Use the linter for real bugs, not for taste. Turn on the strictest type checking your language offers. Run all of it in CI and in the hooks above. This idea has no famous author because it is simple. It is in the first tier because it removes a whole category of review comments, for people and agents alike.

6. One shared vocabulary. Eric Evans, in Domain-Driven Design, calls it the ubiquitous language: the people who know the business and the people who write the code use the same words for the same things, and the code uses those words too (Domain-driven design). If the business says "booking", the type is Booking, the folder is booking/, and nobody writes Reservation in one file and Order in another. This is the useful part of the word ontology, which means a formal list of the things in a field and how they relate. A project needs a short glossary file and names that match it, not a formal ontology language. For an agent, the glossary is the difference between finding the right file and inventing a third word.

7. Small, reversible steps. Make changes small enough to review in minutes and to undo in seconds. Kent Beck's Tidy First? gives a short rule for it: first make the change easy (a small clean-up), then make the easy change (Tidy First?). Nicole Forsgren, Jez Humble and Gene Kim's research in Accelerate found that teams who release small changes often are also the teams with fewer failures (Accelerate). An agent can produce a large change very fast. That is a reason to keep each step small, not a reason to accept large ones.

8. Write down decisions. When you choose between real alternatives (a library, a design, a convention), write a short record of what you chose and why. Michael Nygard named this format the architecture decision record (ADR) (Documenting Architecture Decisions). An agent starts every session with no memory. Without the record, it may "improve" the code back to the option you rejected last month.

The table summarises how each idea gives feedback, and how fast that feedback is.

IdeaWho wrote it downHow a mistake shows upHow fast
Deep modulesOusterhout, ParnasFewer places to break; dependency rules in CIAt review or CI
Wrong states impossible to writeMinsky, KingType errorWhile typing
Functional core, imperative shellBernhardtFast, simple tests failSeconds
Test behaviour through the outsideBeck, DoddsA test failsSeconds
Let tools settle style(common practice)Formatter, linterOn save
One shared vocabularyEvansWrong word in a reviewAt review
Small, reversible stepsBeck; Forsgren, Humble, KimA small, readable changeMinutes
Write down decisionsNygardThe record contradicts the changeAt review

The second tier: useful once the first is in place

These ideas are good, but they depend on the first tier or matter mostly in larger systems.

  • Ports and adapters. Alistair Cockburn's hexagonal architecture puts the core of the application in the middle and connects every outside system (database, web, email) through a small interface, called a port, with one adapter per real system (Hexagonal architecture). It is the functional-core idea applied to a whole application, and it makes the outside systems easy to replace in tests.
  • Prefer copying to the wrong abstraction. Sandi Metz: "duplication is far cheaper than the wrong abstraction" (The Wrong Abstraction). Wait until you see the same code three times before you combine it. This is the rule that stops a "shared foundation" from becoming a heavy framework.
  • You aren't gonna need it (YAGNI). Don't build a feature or an option before a real need appears (Martin Fowler on YAGNI). Agents add "just in case" options easily, so this needs saying.
  • Domain modelling with types. Scott Wlaschin's Domain Modeling Made Functional joins two first-tier ideas, the shared vocabulary and wrong states impossible to write, into one method (Domain Modeling Made Functional). It is the best single book for this way of working.
  • Errors as values, and visible failures. Return an error as a normal value that the caller must handle, instead of throwing an exception (stopping the function and hoping some other code handles the error). Log enough at the edges to see what failed. Both make failures show up instead of hiding.

Is SOLID still solid?

SOLID is the most quoted list of design principles, collected by Robert C. Martin in the early 2000s for object-oriented code, where programs are built from classes; Michael Feathers later gave it the name (SOLID). It has five rules, one per letter:

  • Single responsibility: a class should have one reason to change.
  • Open/closed: code should be open to extension but closed to modification, so you add behaviour without editing what exists.
  • Liskov substitution: anything that claims to be a kind of X must work wherever an X is expected.
  • Interface segregation: many small interfaces are better than one large one.
  • Dependency inversion: high-level code should depend on an interface, not on the concrete low-level code.

Some of these hold up well today. Others are too vague to check, or push code in the wrong direction when followed strictly:

RuleVerdictWhy
Dependency inversionKeepAt the edge of the system it is the same idea as ports and adapters.
Liskov substitutionKeepA real rule that type checkers can partly enforce.
Single responsibilityToo vague"One reason to change" depends on who you ask, so two reviewers disagree.
Interface segregationUse with careFollowed strictly, it produces many tiny interfaces: shallow modules.
Open/closedUse with careTaken literally, it adds layers for changes that never come, against YAGNI.

So SOLID is worth knowing, as shared vocabulary. It shouldn't be the first list you teach an agent. When it conflicts with deep modules, deep modules should win.

What to skip, or keep only as vocabulary

A few famous ideas cost more than they give in a small or medium project:

  • Very small functions everywhere. Clean Code advises functions of a few lines each. Split that far, the code becomes many shallow pieces, and the reader (or the agent) has to jump between them to follow one idea. Ousterhout and Martin argued this in public, and the discussion is worth reading in full (A Philosophy of Software Design vs Clean Code).
  • Design patterns as a goal. The classic catalogue of patterns (factory, strategy, visitor) is useful as names to talk about code. Adding a pattern because it exists, not because the code needs it, makes the code longer and no clearer.
  • The heavy parts of domain-driven design. The shared vocabulary is very useful. The full set of building blocks (the book's many named patterns, such as aggregates and repositories) is worth its cost only in large, complex businesses.
  • Formal ontologies. Formal languages for describing a field, such as the Web Ontology Language (OWL), are built for sharing knowledge between systems, not for organising one codebase. A glossary is enough.
  • Microservices by default. Splitting a system into many small services adds networks, deployments and failures between them. Start with one well-structured program with deep modules inside. Split it only when a real need appears.

Putting the two halves together

The two halves meet in one place: each first-tier idea should end up as an automatic check, not only as a sentence. The diagram shows where each idea is enforced.

Flowchart

The ideas that can't become checks (the shared vocabulary, small steps, decision records) go in the shared set of skills: the review skill asks about them, and the planning skill reminds the agent to keep steps small.

To build the foundation, work in this order:

  1. Add the automatic checks to one project: formatter, linter, strict types, a few behaviour tests, all in CI.
  2. Write the four hooks once, at user level, so every project gets them.
  3. Move the workflow skills into one shared package, and delete the copies in each project.
  4. Write a short principles file with the first-tier ideas in that package, and let each project add only its own rules on top of it.
  5. Turn your most important design rule into a dependency check.
  6. Add example tasks for your shared skills, and run them after every change.

After that, a new project starts from the foundation instead of from an empty folder. That is the whole point: write each rule once, in the place that enforces it, and spend your effort on the work that is new.

References

  1. Anthropic, Hooks reference — Claude Code documentation
  2. Anthropic, Extend Claude with skills — Claude Code documentation
  3. Anthropic, Connect Claude Code to tools via MCP — Claude Code documentation
  4. Anthropic, Plugins overview — Claude Code documentation
  5. Neal Ford, Rebecca Parsons, Patrick Kua and Pramod Sadalage, Building Evolutionary Architectures
  6. Sander Verweij, dependency-cruiser — GitHub
  7. John Ousterhout, A Philosophy of Software Design — WorldCat
  8. Information hiding — Wikipedia (on David Parnas, 1972)
  9. Yaron Minsky, Effective ML Revisited — Jane Street Blog
  10. Alexis King, Parse, don't validate
  11. Gary Bernhardt, Functional Core, Imperative Shell — Destroy All Software
  12. Gary Bernhardt, Boundaries — Destroy All Software
  13. Kent C. Dodds, The Testing Trophy and Testing Classifications
  14. Why Prettier? — Prettier documentation
  15. Domain-driven design — Wikipedia (on Eric Evans's book)
  16. Kent Beck, Software Design: Tidy First? — Substack
  17. Nicole Forsgren, Jez Humble and Gene Kim, Accelerate — IT Revolution
  18. Michael Nygard, Documenting Architecture Decisions — Cognitect
  19. Alistair Cockburn, Hexagonal architecture
  20. Sandi Metz, The Wrong Abstraction
  21. Martin Fowler, Yagni
  22. Scott Wlaschin, Domain Modeling Made Functional — Pragmatic Bookshelf
  23. SOLID — Wikipedia
  24. John Ousterhout and Robert C. Martin, A Philosophy of Software Design vs Clean Code — GitHub

Found it useful? Pass it on.

XLinkedIn

Spotted a mistake? Suggest an edit on GitHub