The old argument for clean code was human. Keep functions small because people need to read them. Name things plainly because people need to find them. Reduce duplication because people need to change behavior in one place without guessing which copy is live.
That argument still holds. But the economics have changed.
If coding agents are now regular participants in your codebase, maintainability is no longer only a human productivity concern. It is also an AI operating-cost concern. Messy code makes agents spend more time reading, more time circling back to the same files, and more tokens carrying the conversation forward.
That is my Interpretation of the SonarSource paper Does Code Cleanliness Affect Coding Agents? A Controlled Minimal-Pair Study. The headline result is easy to misread: cleaner code did not improve Claude Code’s pass rate in their benchmark. But cleaner code did reduce the agent’s operational footprint. The agents used about 7-8% fewer tokens and revisited files about 34% less often when working in cleaner repositories.
That is not a small footnote. In agentic development, the bill is mostly repeated input context. Every loop where an agent reopens a file, re-reads surrounding code, rethinks a plan, or sends a longer conversation history compounds cost. A cleaner codebase may not make today’s model magically smarter, but it can make the same model do less wasteful work.
The Question the Study Actually Asks
Most coding-agent benchmarks hold the codebase fixed and compare agents, models, prompts, or harnesses. That is useful, but it hides a practical question teams care about:
Does the shape of the codebase itself change how an agent behaves?
The paper tries to isolate that variable. It does not compare one random clean project against one random messy project. That would be too noisy. Different projects have different architectures, languages, dependencies, test coverage, and task surfaces.
Instead, the authors built minimal pairs : repository pairs intended to match on architecture, dependencies, behavior, and public interface while differing in static-analysis violations and cognitive complexity. Some pairs started clean and were degraded. Others started messy and were cleaned. The goal was to compare two versions of essentially the same software where the main changed variable was maintainability.
They then created 33 tasks across six repository pairs and ran 660 Claude Code trials , grading final results through hidden tests at the application’s public surface. That setup matters because agent work is not a single prompt asking for a function. It is a multi-turn process where the agent explores files, edits code, runs commands, and decides where to look next.
The study focused on three broad questions:
- Does cleanliness change whether the agent solves the task?
- Does cleanliness change the resources the agent consumes?
- Does the effect differ between localized tasks and tasks that cross module boundaries?
The answer to the first question was mostly no. The answer to the second was yes.
The Pass Rate Result Is Not the Whole Story
It is tempting to collapse the paper into “clean code does not matter because pass rate did not change.” That reading is too blunt.
Pass rate is a narrow outcome. It answers whether the final state passed the hidden task tests. It does not fully describe how much work the agent needed to get there, whether the final patch was easy to review, whether unrelated behavior stayed intact, or how many future sessions will pay for the same complexity again.
The study’s more interesting result is that clean code changed the agent’s navigation pattern.
Agents in cleaner repositories used fewer tokens. They revisited files less. They had a smaller footprint while reaching similar pass outcomes. In normal engineering terms, the task still got done, but the route through the codebase was shorter and less circular.
That matches how agents actually fail in daily use. They rarely fail only because they cannot write syntax. They fail because they lose the thread:
- they inspect the wrong file first
- they infer the wrong abstraction boundary
- they patch a local symptom instead of the source
- they duplicate behavior because the existing helper is hard to discover
- they keep reopening files because names and structure do not stay in memory
Clean code helps by making the next useful action more obvious. That is useful for humans. It is also useful for tools that operate by reading, compressing, and re-reading context.
Why Tokens Track Codebase Friction
Token usage is not just a billing metric. It is a rough measure of friction.
An agentic coding session spends tokens on:
- reading files
- summarizing what it found
- carrying prior turns forward
- planning edits
- explaining commands and failures
- retrying after bad assumptions
- comparing possible locations for a change
Some of that is productive. The agent has to understand the system. But some of it is avoidable search cost.
If a feature is implemented through a clear route of named functions, narrow modules, predictable data flow, and localized tests, the agent has fewer plausible places to inspect. If the same behavior is scattered through long methods, ambiguous helpers, hidden side effects, and duplicated conditionals, the agent has to build a map every time.
This is where code cleanliness becomes a cost control. You may not see it in a single run. A 7% token reduction on one task is not a strategy by itself. But teams do not run one task. They run hundreds or thousands of agent sessions across the same repositories. The same unclear boundary can be re-paid every day by every engineer and every agent.
Sonar’s follow-up post, Your AI bill is a code quality problem, frames this as a budget issue: teams often respond to agent cost by changing models, tuning prompts, or adding usage caps. Those levers matter. But they target the AI side only. Code quality targets the work surface the agent is forced to navigate.
That is the important shift. Refactoring now has a second return:
- humans understand and modify the system faster
- agents spend fewer tokens and fewer loops doing the same work
File Revisits May Be the Stronger Signal
The 34% reduction in file revisitation is more revealing than the token number.
File revisits usually mean uncertainty. The agent opened a file, left it, then came back because the first pass did not settle the question. Sometimes that is healthy. Software work often requires cross-checking. But high revisit rates can also signal that the repository is forcing the agent to rediscover context.
For a human, that looks like flipping between tabs because no file owns the concept cleanly.
For an agent, it looks like repeated reads, repeated summaries, and longer context windows.
The paper’s result suggests cleaner code gives the agent a more stable mental map. It can inspect a location, extract the needed fact, and move on. That does not prove cleaner code always produces better patches, but it does show that maintainability affects agent behavior before the final test result is known.
This matters because many teams evaluate AI coding tools only by merge rate or acceptance rate. Those metrics miss the cost of reaching the merge. A patch that passes after a long wandering session is not equivalent to a patch that passes after a direct one, especially if the same repository will be worked on again tomorrow.
The Limitations Are Real
The study is useful, but it should not be overclaimed.
The public discussion thread raised fair concerns. One major critique is that the repository pairs were themselves produced through agent pipelines that degraded or cleaned code. That is practical for controlled experiments, but it may not fully resemble how real legacy systems become messy. Real systems accumulate social history, partial migrations, old product constraints, abandoned abstractions, and inconsistent local conventions.
Another critique is test coverage. The tasks were graded with hidden tests at the public surface, but the study did not assert that every unrelated behavior in each final patch was checked. A solution can pass the task-specific hidden tests while still damaging behavior outside the grading harness. That is not a reason to ignore the result, but it is a reason to treat pass rate as a limited measure.
There is also a model and tool boundary. The experiment used Claude Code with Claude Sonnet 4.6. Other agents may navigate differently. A model with better retrieval, a stronger planning loop, or a different editing harness may show a different sensitivity to cleanliness. The benchmark is valuable partly because it gives future work a way to test that.
So the cautious conclusion is:
Cleaner code did not improve task pass rate in this setup, for this agent, on these tasks. It did reduce operational footprint.
That is enough to be useful.
What This Means for Engineering Teams
The practical takeaway is not “stop caring about models.” Model choice, prompt design, caching, tool permissions, and evaluation harnesses still matter. They may matter more in absolute cost terms than any one refactoring campaign.
The takeaway is that code quality has entered the same budget conversation.
If your team is serious about coding agents, you should treat the codebase as part of the agent runtime. The repo is not inert input. It shapes the agent’s search path, context length, retry loop, and patch strategy.
That changes how some maintenance work should be justified.
Cleaning up a complex module is no longer only a bet that a future human will save time. It is also a bet that every future agent run over that module will spend less time reconstructing intent. Renaming a vague helper is not only aesthetics. It is a retrieval improvement. Splitting a giant function is not only style. It gives both human and machine readers smaller units to reason about.
The best candidates for cleanup are places agents touch repeatedly:
- core business logic with frequent product changes
- integration layers with many similar APIs
- configuration and deployment code
- test utilities and fixtures
- modules where agents often duplicate existing behavior
- files that appear in many failed or long-running agent sessions
Do not refactor everything because a paper found a token delta. Refactor where repeated navigation cost is visible.
Clean Code for Agents Looks Like Clean Code for Humans
The most reassuring part of the result is that it does not require a strange new style of code written for machines.
The same habits still apply:
- small functions with honest names
- low cognitive complexity
- clear module ownership
- fewer hidden side effects
- consistent naming conventions
- tests that define behavior at useful boundaries
- removal of dead paths and stale abstractions
- one canonical place for each important concept
There is no need to make code more verbose just to explain it to an agent. There is also no need to stuff repositories with redundant comments describing obvious syntax. Agents benefit from structure, not noise.
The right target is code where intent is recoverable from names, boundaries, and tests. Comments should explain decisions that are not visible in the code: constraints, tradeoffs, invariants, protocol assumptions, and reasons a simpler-looking change is wrong.
That style helps agents because it helps any reader build a stable map.
The New Maintenance Argument
For years, teams have treated maintainability as something they believe in but struggle to fund. Product work has obvious deadlines. Cleanup has diffuse benefits. The cost of mess is real, but it is hard to invoice.
Agentic coding makes some of that cost measurable.
If messy modules cause agents to consume more tokens, revisit more files, and spend more turns reaching the same result, then code quality shows up in infrastructure spend and engineering throughput. It becomes part of the operating model, not just a taste debate.
This does not mean every cleanup pays for itself. It means the old tradeoff has new data attached.
The next useful step for teams is local measurement:
- track which files agent sessions read most often
- record where agents revisit files repeatedly
- compare token usage for tasks in clean versus messy subsystems
- watch for duplicated patches that missed existing helpers
- connect long-running sessions to specific codebase regions
That data can turn “this module feels bad” into “this module repeatedly increases agent cost and review risk.”
The Bottom Line
The paper does not prove that clean code makes agents solve more tasks. It shows something narrower and more immediately useful: clean code can make agents spend less effort doing the same work.
That is enough to change the maintenance conversation.
When humans were the only readers, clean code paid back through comprehension. When agents become regular readers and editors, the same cleanliness also pays back through lower token usage, fewer navigation loops, and less repeated rediscovery.
The codebase is now part of the agent stack. Treating it that way is likely to matter more than another round of prompt polish.

Top comments (0)