Lesson 21 of 40Quality loops
Clean Code with AI
Recognise the mess AI tends to leave in a codebase, prevent it with prompts and gates, and review AI diffs with a checklist.
AI-written code usually works. The trouble is what comes with it: a second date formatter next to the one you already had, a factory class for something that needed one function, comments that repeat the code, and a 900-line diff for a 20-line change. None of it fails a test, so it piles up. Six months later the codebase is twice the size, nobody knows which helper is the real one, and every change is slower, for humans and for AI. This lesson names the usual mess, explains why it happens, and gives you habits and a checklist to stop it.
The usual suspects
Here is what to look for in an AI diff. Each item looks harmless alone.
| Smell | What it looks like |
|---|---|
| Duplicated helpers | A new formatPrice() when formatMoney() already exists in lib/format.ts |
| Invented utilities | A hand-written debounce or deep-clone when the project already has one, or the language has it built in |
| Dead code | Functions nothing calls, old versions left "just in case", unused imports and parameters |
| Over-engineering | An interface, a factory and a config object for one code path that will never vary |
| Inconsistent style | async/await in a file that uses promise chains, a new naming scheme, a different error pattern |
| Comment noise | // increment i above i++, or comments narrating the change: // now using the new helper |
| Giant diffs | Renames, reformatting and unrelated "improvements" mixed into a small fix |
The duplicated helper is the most common and the most costly. Here is a typical case:
- src/
- lib/
- format.tsformatMoney(cents): the real one, used in 14 files
- features/
- checkout/
- utils.tsformatPrice(amount): new, from the AI, used once
- Summary.tsx
Both functions turn a number into a price string. One takes cents and one takes dollars. Next month someone fixes a rounding bug in one and not the other, and the checkout page disagrees with the receipt.
EmailStrategy, EmailStrategyFactory, WelcomeEmailStrategy and a config file. The app sends one kind of email. What is the best name for this problem?Why AI does this
None of this is malice or stupidity. It follows from how the tools work.
- The model only knows what is in its context. If it never opened
lib/format.ts, then as far as it knows, there is noformatMoney. Writing a new helper is the reasonable move from where it stands. - Writing is cheap and searching costs effort. Producing ten new lines is easier than grepping the repo, reading three files and reusing one.
- It is trained to be thorough and helpful. Extra validation, extra options and extra comments look helpful in a single answer, even when they hurt the codebase.
- It does not feel the maintenance cost. You will read this code for years. The model will not remember it tomorrow.
So the fix is mostly about context and constraints: tell it what exists, make it look before it writes, and put checks in its way.
Prevention habits
Make it search first. Put this in the prompt, or better, in your project memory file so it applies every time:
## Code rules
- Before writing a helper, search the codebase for an existing one (grep for the verb:
format, parse, fetch, validate). Reuse it or extend it. Say what you found.
- Shared helpers live in src/lib/. Do not create utils files inside features.
- Smallest change that solves the task. No drive-by refactors or reformatting.
- No comments that restate the code. Comment only on why, never on what changed.
- Delete code you replace. Do not leave old versions or commented-out blocks.Keep diffs small. Ask for one step at a time and check the size with git diff --stat before reading. If a "small fix" touches 15 files, stop and ask why. Small diffs are easier for you, for a reviewer, and for the model itself.
Let tools enforce what tools can. A linter catches unused imports and variables. A type checker catches mismatched shapes between the old and new helper. Run them automatically with a hook, as shown in the build, test, review loop lesson, so the model sees the errors and fixes them itself.
Ask for a simplification pass. After the feature works, a second prompt: "Simplify this change. Remove anything not needed for the task, reuse existing helpers, and delete dead code. Do not change behaviour; tests must still pass." In Claude Code, /simplify is a built-in command for exactly this kind of pass. A reviewer with a fresh context is also good at spotting duplication, because it reads the diff cold.
Delete code. The cheapest code to maintain is code that is gone. When the AI replaces something, the old version goes in the same commit.
Project memory sets the rules once, for every session. It is the cheapest layer because you write it once.
Match each smell to the habit that best prevents it.
When the diff is already huge
Sometimes you get the giant diff anyway. Do not try to review 40 files in one sitting; you will skim, and skimming is how mess gets merged. Instead:
- Look at the shape first.
git diff --statlists every file and how many lines changed. Files that have nothing to do with the task are your first suspects. - Ask the AI to explain the scope. "List every file you changed and the reason for each. Mark any change not needed for the task." Models are fairly honest about this when asked directly.
- Split or revert. Ask it to revert the unrelated changes, or to split the work into separate commits: the feature, then any refactor, then formatting. Each commit should make sense on its own.
- Review the core change carefully, the rest quickly. Once formatting and renames are isolated, the real logic is often a few dozen lines.
If the diff cannot be explained, throw it away. Run /rewind or reset the branch, tighten the prompt, and try again in a fresh session. Regenerating a clean change usually takes less time than untangling a messy one.
A review checklist for AI diffs
Use this every time you read an AI change. It takes a few minutes and catches most of the mess.
- [ ] Size: does the number of files and lines fit the task?
- [ ] Reuse: does any new function duplicate one that already exists? (grep its verb)
- [ ] Scope: is every change needed for this task? Revert drive-by edits.
- [ ] Dead code: unused functions, params, imports, commented-out blocks?
- [ ] Abstractions: is each new class, interface or option used by more than one real case?
- [ ] Style: does it match the neighbouring code (naming, errors, async style)?
- [ ] Comments: do they explain why, or just repeat what?
- [ ] Tests: do the tests check behaviour, not implementation?A tiny duplicate detector
Duplicated logic often shows up as repeated lines. Real tools for this exist for every language, but the idea is simple enough to write yourself. This detector normalises each line (strips spaces, skips blank lines and lone brackets) and reports any line that appears in more than one place.
Press Run (⌘ Enter) to see what happens.Both body lines match even though the function names differ, which is exactly the shape of a duplicated helper. Real duplicate finders compare blocks of several lines, or the code's structure, to cut out noise like repeated import lines. Try adding a third file with the same return line and run it again.
What does this print?
lines = ["a = 1", " a = 1", "b = 2", "a=1"]
print(len({" ".join(l.split()) for l in lines}))None picked yet
- duplicated helper
- A new function that does the same job as one already in the codebase.
- dead code
- Code that never runs or is never called, but still has to be read and maintained.
- over-engineering
- Abstractions and options built for variation that does not exist yet.
- comment noise
- Comments that restate the code or narrate the change instead of explaining why.
- diff
- The set of line-by-line changes between two versions of the code.
- simplification pass
- A follow-up step that removes unneeded code without changing behaviour.
- linter
- A tool that flags suspicious or unused code and style problems without running it.