Writing
Code Refactoring: When It Pays and When It Doesn’t
Refactor in small bursts while you add features and fix bugs, with tests in place first. Weeks spent polishing working, readable code buy nothing, and AI tools make big refactors cheap to write but expensive to review.
By Ka Lun Chan · Engineering judgment / Delivery
When should you refactor code?
Refactor when it helps you do the work in front of you: adding a feature, fixing a bug or speeding up the next change. Do it in small steps, with tests in place first, and leave working, readable code alone. Refactoring for its own sake, or to avoid criticism, costs time and money and buys nothing.
I first wrote this on my old blog. This version keeps the advice that held up and updates what changed, mostly around AI coding tools and how refactors get reviewed.
| Situation | Refactor now? | Why |
|---|---|---|
| You’re about to add a feature and the code fights you | Yes, first | Make the change easy, then make the change. The refactor pays for itself in the same piece of work. |
| You’re fixing a bug in code you can barely follow | Yes, a little | Clarify just enough to understand the bug. A clearer function is also where the regression test goes. |
| The code works, is readable and nobody is changing it | No | There’s no payoff. This is where weeks disappear for no business value. |
| You want it to look good before someone else reviews it | No | Fear of criticism isn’t a reason. Ship readable code and learn from the feedback. |
| There are no tests around the code | Not yet | Write characterization tests first. Without them you can’t tell a refactor from a behaviour change. |
| An AI tool offers to restructure the whole module | Only in slices | Generating it is cheap. Reviewing it isn’t. Take it one reviewable pull request at a time. |
| The same mess slows every sprint and a rewrite is being discussed | Yes, incrementally | Refactoring the hot spots is usually cheaper and safer than rewriting. |
What does refactoring actually buy you?
Code that’s easier to read and less complex, which makes the next change cheaper. The behaviour stays the same. If the behaviour changes, it’s a rewrite or a feature, and it needs to be reviewed as one.
Martin Fowler’s definition is the one I still use: a change to the internal structure of software that makes it easier to understand and cheaper to modify, without changing what it does from the outside. That last part is the discipline. Renaming, extracting a function, splitting a class, removing duplication: each of these should leave every caller and every user seeing exactly what they saw before.
The payoff comes later, in the form of the next person reading the code in minutes instead of an afternoon. That’s why readability and lower complexity were my reasons for refactoring when I first wrote about it, and they still are.
Can you spend too much time refactoring?
Yes. No developer writes perfect code, and chasing it means spending real money on changes nobody needed. Clean code comes from habit and experience, not from repeated passes over code that already works.
Many years ago I hired a developer who loved writing perfect code. He would spend weeks refactoring something that was already working and readable. The code did get prettier. It wasn’t worth the money or the time, because none of that effort made the product better or the next feature faster.
The other trap is refactoring out of fear. If you polish code because you’re worried about what other developers will say in review, you’ll never finish. Ship code that’s readable and correct, then take the criticism as information. I wrote more about learning from criticism, failure and mistakes in how to be a better developer.
Why write tests before you refactor?
Because refactoring can break working code, and tests are how you know it didn’t. Without them, a refactor is a behaviour change you haven’t noticed yet.
Fowler makes the same point in Opportunistic Refactoring: the practice depends on a solid test suite, and adding tests to a weakly tested area before you change it is reasonable. For old code with no tests, I start with characterization tests. They don’t assert what the code should do. They record what it does today, including the odd cases, so any difference after the refactor shows up as a failure.
# Pin down what the code does today before restructuring it.
# invoice_total is an illustrative function; the expected values are
# whatever the current code returns, even the surprising ones.
import pytest
from billing import invoice_total
@pytest.mark.parametrize(
("items", "coupon", "expected"),
[
([], None, 0),
([("widget", 2, 500)], None, 1000),
([("widget", 2, 500)], "SAVE10", 900),
([("widget", 1, 500)], "EXPIRED", 500),
],
)
def test_invoice_total_keeps_current_behaviour(items, coupon, expected):
assert invoice_total(items, coupon) == expectedRun the tests, refactor in a small step, run them again. If one fails, either the refactor changed behaviour or the old behaviour was a bug. Both are worth knowing, but fixing the bug is a separate change.
When is a good time to refactor?
When you’re adding a feature, fixing a bug, speeding up development that has started to drag, or when refactoring is cheaper than a rewrite. In each case the refactor serves another piece of work.
- Adding a feature. Fowler calls this preparatory refactoring, and his worked example credits Kent Beck with the summary: make the change easy first, then make the easy change.
- Fixing a bug. Clarify the code enough to understand the failure, then fix it with a test.
- Speeding up development. If every change in one area takes twice as long as it should, the friction is the signal.
- Instead of a rewrite. Incremental refactoring keeps the behaviour the old system has accumulated. I covered the tradeoff between refactoring, replacing and rewriting in when technical debt becomes a business problem.
When I first wrote this, I quoted Fowler at length on not setting aside weeks for refactoring. His current writing still says the same thing in fewer words: “a team that’s using refactoring well should hardly ever need to plan refactoring.” He does allow that planned and long-term refactoring are occasionally needed, and his workflows of refactoring list them alongside the everyday kinds. I agree. Occasionally is the important word.
What changes when an AI tool does the refactoring?
Large refactors are now cheap to generate and just as expensive to review. That makes tests and small pull requests more important, not less.
An AI coding agent can rename a concept across a hundred files or restructure a module in a few minutes. The hard part used to be typing it. Now the hard part is knowing that nothing changed except structure. A two-thousand-line diff labelled “refactor” gets skimmed, and a single changed condition hidden in it becomes a production bug.
The rules I use:
- Keep refactors in their own pull requests. Google’s small CL guidance says the same: move or rename in one change, fix the bug in another, so the reviewer can follow each.
- Ask the agent for a sequence of small steps, each passing the tests, instead of one big rewrite. It’s the same argument I made in smaller user stories and pull requests.
- Have the tests in place before the agent starts. A tool that can change the tests and the code in the same diff can make anything pass.
- Match review depth to risk. A rename in a utility module is not a refactor of payment or authorization code. How deep to verify AI-generated code covers that scale, and code review in the AI era covers what people still need to check.
Why are small refactors better than big ones?
Small refactors are easy to review, easy to revert and fit inside real work, so they actually happen. Big ones stall, collide with feature branches and get abandoned halfway.
I’m a fan of small refactoring to keep code clean and maintainable. Rename the confusing variable while you’re in the function. Extract the block you had to read three times. Leave the code a little better than you found it, which Fowler calls the camp site rule. Over months, those small changes add up to a codebase people can work in, without anyone ever asking for a refactoring sprint. The principles behind that, such as keeping things simple and not repeating yourself, are in programming principles every developer should know.
Sources
Checked in November against Martin Fowler’s definition of refactoring, his Opportunistic Refactoring entry, his preparatory refactoring example and Workflows of Refactoring, and Google’s engineering practices on small changes. The hiring story, the decision table and the recommendations are mine.
Short answers
When should you refactor code?
When it helps the work in front of you: adding a feature, fixing a bug, or speeding up changes in an area that has started to drag. Do it in small steps with tests in place, and leave working, readable code alone.
Should you write tests before refactoring?
Yes. Refactoring can break working code, and tests are how you know the behaviour stayed the same. For untested code, start with characterization tests that record what the code does today.
Should teams schedule refactoring sprints?
Rarely. Martin Fowler argues that a team refactoring well should hardly ever need to plan it, because small refactors happen alongside features and bug fixes. Planned refactoring is occasionally needed, but it should be the exception.
How do AI coding tools change refactoring?
They make large refactors cheap to generate and expensive to review. Keep refactors in their own small pull requests, have tests in place before the tool starts, and match the depth of review to the risk of the code being changed.
Refactor on the way to something
Next time you open a pull request, look for one small cleanup that made your change easier, and put it in its own commit with the tests passing before and after. That habit does more for a codebase than any refactoring sprint.