You want to change messy code without breaking it. Here is how to refactor code: make small behavior-preserving changes, one at a time, with passing tests behind you, and commit each step on its own.
This guide is one of the spokes in our collection on software development best practices.
| Item | Value |
|---|---|
| What refactoring is | A controlled technique for improving the design of an existing code base |
| Size of each change | Small behavior-preserving transformations |
| Test state while refactoring | Green: all tests passing |
| Refactorings detailed in Fowler’s book | Around seventy |
| Book editions | First edition 1999; second edition late 2018 |
These figures come from Martin Fowler’s book page and his Workflows of Refactoring deck. They can change, so check the source before you rely on them.
What refactoring actually means
Martin Fowler describes refactoring as a controlled technique for improving the design of an existing code base, built from a series of small behavior-preserving transformations (book page). Each step can feel too small to bother with. The cumulative effect, though, is quite significant.
The test that separates refactoring from other work is observable behavior. A refactoring changes the internal structure of the code without modifying how it behaves from the outside (Understand Legacy Code). That means fixing a bug or adding a feature is not refactoring, and refactoring preserves bugs too.
Kent Beck’s advice fits neatly here: for each desired change, make the change easy (warning: this may be hard), then make the easy change. In practice you refactor first, and then fix the bug or add the feature.
Our explainer on what is technical debt looks at the wider cost of leaving messy code in place.
Build a safety net before you touch anything
To know you have refactored successfully, you must know whether behavior changed. That makes automated tests the first requirement. If you have none, spend time writing them for the part you intend to refactor (Understand Legacy Code).
For legacy code, characterization tests are usually the first step: they pin down what the code currently does, quirks included, before you change its shape (Sourcegraph). Their job is to describe today’s behavior, not to judge it.
Several tools give you early warning when something breaks:
- A test suite that runs quickly and passes before you start.
- Static types and linters, which give early feedback about something that no longer works and raise your confidence in refactoring.
- Version control, so you can stash work in progress and get back to a clean state.
Fowler’s rule is simple: you only refactor with green tests, and any failing test indicates a mistake (Workflows of Refactoring). If work in progress is causing failures, stash it or temporarily disable it first. Agreeing on a code style guide beforehand also helps keep formatting edits separate from structural ones.
How to refactor code step by step
The routine below combines advice from Fowler’s workflow deck, a classic patterns wiki and practitioner write-ups. Follow it in order and keep each loop short.
- Get to green. Run the tests. If unfinished work is breaking them, stash or disable it first.
- Pick your hat. Decide that this session is refactoring only, with no new behavior mixed in.
- Find the smallest useful change. Make it, then test it.
- Repeat in tiny steps. Compile and run the tests after every change so a mistake is easy to locate.
- Commit refactorings in isolation. Keep them apart from behavior changes, ideally in their own pull request.
- Stop when the change you need is easy. If the refactoring grows longer than is reasonable, stash it and come back to it later.
Fowler’s metaphor is that you can only wear one hat at a time: either you are refactoring or you are adding function (Workflows of Refactoring). You may swap hats often, but never wear both at once.

Small steps matter because bigger refactorings are like labyrinths without exit: you get lost after a few steps. Work in tiny increments and you can stop at any point in time, which is useful when a must-have feature lands unexpectedly (Refactoring In Very Small Steps).
Industrial Logic’s write-up splits a single refactoring into three phases: Prepare, Improve and Clean. Each phase is optional, because the code may already be ready for the improvement or need no tidying afterwards (Industrial Logic). It is a handy way to think about a change that feels too large to start.
One more check helps: if you have to change your tests while “refactoring”, you are probably doing something else. Refactoring is improving existing code without changing behavior, so tests shouldn’t have to change (Learn Go with Tests).
Refactoring techniques worth learning first
Fowler’s book gives the motivation, mechanics and a simple example for each refactoring, and several development environments now automate many of them (book page). Start with a handful of everyday moves:
- Extract method: pull a coherent fragment out of a long method and give it a name that says what it does.
- Rename: naming things for what they do removes a translation layer every future reader pays for.
- Inline method: when a method’s body is as clear as its name, and the indirection adds nothing, fold it back in.
- Replace temp with query: swap intermediate variables for well-named methods so logic lives in one place.
- Guard clauses: replace nested conditionals with early returns to flatten the arrow.
The techniques above are described in Sourcegraph’s guide to refactoring techniques. Use them when a smell points you there rather than as a checklist to apply everywhere.
Code smells are the visible symptoms that suggest which move to reach for. Data clumps are a good example: when you see the same parameters passed around together, they would probably be better joined into a single abstraction (Understand Legacy Code). Once you have learned some moves you may be tempted to apply them everywhere, and the advice is not to.
When to refactor and when to leave code alone
The best moments are the ones where cleaner code pays off straight away:
- Before adding a feature, to make that feature easier to add.
- While working out how some code behaves, since actively interacting with it teaches you more than passively reading it.
- As planned time, when a bigger refactoring would take too long to do in small chunks.
- Whenever you touch a messy area, following the camp site rule (Workflows of Refactoring): always leave the code better than when you found it.
Some code should be left alone. Skip the refactor when the code is scheduled for retirement, when you can’t test the result, or when the only justification is aesthetic preference (Sourcegraph). Ugly code that doesn’t need to change anyway is not worth your time, and neither is something that would be easier to rewrite.
The guiding idea is that productive programmers refactor to keep changing behavior fast, not for the beauty of it (Understand Legacy Code). Tie each refactoring to a change you actually need to make.
Frequently asked questions
Is refactoring the same as rewriting code?
Show answer
No. A refactoring changes the internal structure of the code without modifying its observable behavior, so a rewrite that changes behavior is something different (Understand Legacy Code).
Can I fix a bug while I refactor?
Show answer
Not in the same step. Refactoring preserves bugs, so refactor the code first and then fix the bug, and keep the two changes in separate commits (Understand Legacy Code).
What if the code has no tests?
Show answer
Write tests for the part you intend to refactor before you change it. Characterization tests that pin down current behavior are a common starting point for legacy code (Sourcegraph).
How small should each step be?
Show answer
Find the smallest useful change you can make, make it, then test it (Refactoring In Very Small Steps). Small steps reduce the risk of introducing errors (book page).



