Skip to content
Refactoring is the most underrated application of AI coding

Refactoring is the most underrated application of AI coding

A team writes reducing technical debt into its quarterly goals, and the usual approach is to give everyone access to an AI assistant, then wait for code quality metrics to change. After a quarter, the metrics often barely move, but engineers feel that things really did get easier. These two conclusions aren’t contradictory—it’s just that the work saved wasn’t booked under the “refactoring” account.

What AI actually eats up is the changes whose rules can be stated in one sentence: collecting scattered string constants into an enum, uniformly replacing hundreds of old interface names, wrapping a batch of handlers in the same error-handling layer, converting old-style print statements into function calls. This work used to be either done on overtime or put on the “when there’s time” list, where it sat for two years.

The other part booked under refactoring—whether this module should be split, whether this layer of abstraction is worth keeping, whether two services should be merged—gets wildly varying answers from AI, and you can’t verify whether it’s right. Two kinds of work get lumped under one word, so both the budget and the expectations are misplaced.

The returns on mechanical rewriting are roughly linear and have little to do with how smart the model is

Splitting refactoring into two halves makes things much clearer: the part where rules are decidable, and the part where they aren’t. For the former, the workload is roughly the number of change points times the per-point cost, and the per-point cost is determined by rule clarity and verification methods. Swapping the model from one generation to the next won’t change this part’s returns by an order of magnitude, because the bottleneck is “are the rules written rigidly enough” and “can the verification actually run,” not comprehension.

A common scenario: a backend repo that’s been running for five or six years, where the service layer has dozens of functions each assembling the same response structure, with three different spellings of field names and error codes scattered everywhere. The rules for this kind of rewrite can be written in one sentence, and the number of change points is on the order of several hundred. One engineer with AI can finish it in roughly one to two days, most of which goes to validation and spot-checking, not generation.

Compare that with another task: having AI decide how many pieces this two-thousand-line class should be cut into, where to cut, and how to draw the boundaries. It gives a different plan every time, and no plan can be automatically verified. You can only rely on people reading, discussing, and judging the business’s next six months. The output of this kind of work is a decision, not lines of code; AI’s role here is to offer candidates, not to make the call for you.

For the part of refactoring that can be handed to AI, the returns are roughly proportional to the number of change points and only weakly correlated with model capability; the real variable is whether the rule can be written as a sentence with no “it depends.”

There’s also a counterintuitive phenomenon worth noting: the clearer the rules, the more stable AI’s performance, and the lower people’s trust in it—because what it generates looks too simple. So some teams take this kind of task back and do it by hand, reasoning that “it’s not hard anyway.” That’s waste. Simple doesn’t mean cheap; hundreds of simple changes stacked up is months of debt.

Why nobody does this accounting

The output of mechanical rewriting is a diff, not a feature. It doesn’t go into the requirements list, the release notes, or any delivery metric. Whenever a team asks me where the returns on refactoring are, I can only give an indirect answer: every future change to this code will take less time, and the probability of errors will be lower. That answer can’t go into a quarterly report.

And public discussion of AI coding is heavily concentrated on “can it write new features”—the demos all show an app growing out of an empty directory. So the scenario with the most certain returns and the easiest failure containment is paradoxically the hardest to get approved as a project.

My judgment: refactoring is the most underrated application of AI coding because its return shape is “time saved in the future,” while the vast majority of teams only count “time already spent.” This isn’t a cognition problem; it’s an accounting-basis problem.

What blocks people isn’t the rewriting, it’s deciding which part counts as mechanical

Since the returns depend on rule clarity, the real bottleneck is classification. Here’s a set of criteria you can use directly.

TEXT6 lines
1
2
3
4
5
6
把一段重构交给 AI 之前,逐条过:
1. 规则能用一句话写完,不含“视情况而定”
2. 结果能被编译器、类型检查或现有测试判真假
3. 单次改动的 diff 形状一致,看三处能推知其余
4. 失败是局部的,改错只影响被改的那一处
5. 一次提交能整段 revert,不用手工拆

Item 2 is the one most easily skipped. Many teams think having tests is enough, but tests cover behavior, not shape. If the refactoring changes internal structure, all-green tests may mean the tests never even reach the changed path. Decidable means the machine raises an alarm when something is changed wrong, not that a person discovers it by feel during review. In old projects this is usually the sticking point, so the first step is often not writing rules but getting tests on the critical paths to the point where they can run.

Item 4 determines whether to batch. Renaming a single function is local; swapping the global date handling to a new library is not—time zones, formatting, and serialization boundaries all move with it, and one mistake drags down a whole area. Even if the rules are written very clearly, this kind of change must be split by module and verified batch by batch.

Item 3 is for reviewers. Only when the diff shape is consistent can review extrapolate from a sample to the whole. If a batch mixes three different shapes, review can only go line by line, and the time AI saved gets handed right back.

Item 5 is the safety net. A commit that can’t be rolled back as a whole means that when something goes wrong you can only pick things out by hand, which under the time pressure of incident response is almost guaranteed to go wrong.

Abstraction decisions can’t be outsourced, because the cost lands six months later

A common path goes like this: AI sees that three handlers each have a similar chunk of error handling and quite naturally extracts a shared function. The second change adds a parameter, the third adds a flag, and six months later the function has seven boolean parameters, with each call site passing a different combination. At that point you can’t delete it, and you don’t dare change it.

With abstraction, the benefit is now—duplicate lines drop immediately; the cost is in the future—the coupling surface every future change has to cross gets bigger. AI is only responsible for the former, not the latter, so its default tendency is always to abstract a bit more. This isn’t a flaw in the model; it’s determined by the objective it’s optimized for: ask it to eliminate duplication, and it will eliminate duplication.

The opposite error exists too. To keep things simple, you keep three separate copies of logic that’s clearly identical, and then one requirement change means editing three places, and missing one is a production incident. So the problem isn’t “if a human decides, it’s necessarily right”—it’s that this judgment requires someone to bear the consequences and to see the maintenance cost six months out. Right now that position can only be filled by a human.

There’s a boundary where you can give ground: if the abstraction converges locally—say, a private function extracted within a single file that doesn’t spill out into a shared utility—then AI’s proposal can be used directly. The criterion is the abstraction’s visibility scope; the smaller the scope, the lower the cost of trial and error. A team agreeing “AI may not add cross-module shared abstractions” is far more executable than asking it to “not over-abstract.”

Changes that look mechanical are the most likely to blow up

Converting callbacks to async/await is the most “looks like mechanical rewriting, actually least mechanical” category I’ve seen. On the surface it’s a syntax swap, but in reality the error propagation path changes: exceptions in callbacks may have been swallowed at some layer, and after converting to await they’re thrown straight to the caller; things that used to be guaranteed by callback order are now guaranteed by microtask order, and some timing assumptions stop holding. Branches the tests don’t cover come out green after the change and blow up in production.

Rewrites involving concurrency, error propagation, lifecycle, serialization formats, or transaction boundaries can’t be treated as mechanical, even if the diff is only a few dozen lines.

Batch-adding timeouts and retries to interfaces is the same category. The template is very uniform and fully meets the literal requirement of “rules stated in one sentence,” but retries are a disaster for non-idempotent write interfaces—three retries might place three orders. The rules must spell out the scope of application, and the information “which interfaces are idempotent” isn’t in the code; only the person who maintains the service knows it.

So whether a change is mechanical isn’t judged by diff length or degree of repetition, but by whether it touches state and timing. Highly repetitive but purely literal changes can be handed off; a one-line change that alters execution order cannot.

Pipeline: Humans set rules and templates, AI does the diffusion, humans review the shape

Putting the above points together, the practical form looks roughly like this.

flowchart LR
    A[人写规则] --> B[人改一处样板]
    B --> C[AI 扩散其余]
    C --> D[编译与测试]
    D --> E[人审 diff 形状]
    E --> F{有越界改动}
    F -->|有| C
    F -->|无| G[合并]

The most valuable step in this process is a human revising one template. The template is both an anchor for the AI and an acceptance baseline for the human. Once the template is revised, the implicit constraints in the rules that weren’t clearly written surface: naming conventions, log formats, parameter order, exception types. These things can’t be captured in a one-sentence rule, but they can be reflected in a diff.

My default is to keep a single commit within twenty files and a four-hundred-line diff; split anything beyond that. Not because the model can’t handle a larger volume, but because a human has to review it. Beyond that volume, review degrades from looking at the shape to scanning through, and the miss rate rises noticeably. This number is empirical; teams with high test coverage can relax it, and vice versa.

YAML7 lines
1
2
3
4
5
6
7
task: 统一 handler 错误包装
scope: src/handlers/**/*.ts
rule: 导出函数体用 withErrorBoundary 包裹,签名和返回值不变
exclude:
- src/handlers/health.ts
verify: tsc --noEmit && pnpm test --filter handlers
stop_if: 出现无法自动判定的分支,列清单交回人工

The stop_if line deserves separate mention. For a task without a stop condition, when the AI hits an ambiguous branch it picks a direction and continues on its own, and that direction is often wrong—and it’s buried in hundreds of lines of diff. Explicitly writing “stop and list the items when you hit a certain kind of situation” amounts to handing the judgment back to the human, and it also tells the reviewer where to focus.

The review actions need to change too. Reading the diff line by line is subsidizing the machine with human time; the right approach is to sample three things: whether the template spot is consistent with the rules, whether a random five percent sample is isomorphic, and whether there are out-of-bounds changes (files changed outside the scope). If all three pass, the rest goes to compilation and tests.

How to schedule this quarter’s refactor

First go through each item on the refactor list by “can the rule be stated in one sentence,” and split them into two piles.

The first pile is mechanical rewriting. This pile can be parallelized, compressed, and handed to junior engineers working with AI; the acceptance criteria are compilation passing, tests passing, and sampled diffs being isomorphic. Estimate the schedule by the number of change points, not by gut-feel person-days.

The second pile is design trade-offs. This pile can’t be compressed, and AI shouldn’t lead it. The output is a few candidate approaches and one decision, which requires judgment about the business over the next six months and an estimate of the team’s maintenance capacity. The rhythm is discussion and review, not generation.

Scheduling the two piles together most commonly results in the mechanical part being done quickly, the design part being squeezed, and the final delivery being code that’s neater but a structure that hasn’t improved. Conversely, scheduling only design and not mechanical work means engineers spend a lot of time on low-value repetitive labor, and the refactor itself gets dragged down.

There’s another easily overlooked benefit: once the mechanical rewriting is done, the discussion of the second pile becomes easier. Field names are unified, error codes are converged, readers of the code don’t have to do a mental translation first, and the judgment of where abstractions should be cut becomes more accurate. The two piles aren’t parallel; they have an order.

Before scheduling the refactor into the next iteration, spend half an hour listing that checklist and write down “the one-sentence version of this rule” for each item. The items you can’t write out are the refactors that genuinely need a human this round, and the only part worth a meeting to discuss. The rest goes to the pipeline.

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#AI Coding #Engineering Practices #Refactoring

Comments