What Is Refactoring? Definition, Techniques and Where to Start

Raghav Chamadiya9 min read
On this page

Refactoring is restructuring existing code without changing its external behavior. Martin Fowler defines a refactoring as a change to the internal structure of software that makes it easier to understand and cheaper to modify without changing its observable behavior, and refactoring as the practice of applying a series of those changes. This guide covers what refactoring means, how it differs from a rewrite, the core techniques, how to refactor safely, and how to choose where to start.

What is refactoring?

Refactoring is a change to how code is built, never to what it does. The inputs and outputs stay the same, the tests that passed before still pass, and the users notice nothing. What changes is the shape: shorter functions and clearer names, with logic where a reader would look for it.

Fowler's Refactoring catalog frames it as a sequence of small, behavior-preserving transformations. Each step is tiny enough to be safe, and many steps in a row add up to a large structural change. That is the property that separates refactoring from "cleaning up": every step is verifiable.

The word is used for two things, and it helps to keep them apart. As a noun, "a refactoring" is one named transformation, such as Extract Method. As a verb, "refactoring" is the practice of applying a series of them to improve a design.

Refactoring vs rewrite vs bug fix

A refactor keeps behavior, a bug fix changes it on purpose, and a rewrite replaces the code. Mixing them in one change is the usual way a refactor goes wrong, because a reviewer can no longer tell whether a changed line was meant to alter behavior.

RefactorBug fixRewrite
Changes external behaviorNoYes, to the intended behaviorOften, by accident
ScopeOne function, class or file at a timeThe defect and its causeA whole module or system
Verified byExisting tests, unchangedA new test that failed beforeA new test suite, often from scratch
Can ship in small piecesYesYesRarely
RiskLow per stepLow to mediumHigh

Scroll the table sideways to see every column.

Keep them in separate commits, ideally separate pull requests. "Refactor, then fix" and "refactor, then add the feature" are both fine orderings. A single commit that does all three is the one nobody can review.

A rewrite is sometimes right, for example when the platform is end-of-life. Otherwise, refactor toward the design you want one seam at a time while the old code keeps shipping.

Why refactoring matters

Refactoring pays for itself when the code it touches changes often. The cost of a messy file is paid on every edit: more time to understand it, more chance of breaking something next to it. Refactoring lowers that cost for the next change, and the next. The habits that make code easy to change are laid out in the clean code guide.

It is also how technical debt gets repaid in practice. Debt is a design that no longer fits the code; refactoring is the work of moving the code to a design that does. The related guides on the technical debt quadrant and spaghetti code cover how that debt builds up and what it looks like.

The evidence that structure concentrates risk comes from our own data. We analysed 195 of the most-starred public repositories indexed on repowise.dev (November 2026, production code only). In the median repo, 10% of files take 68% of the line churn over 90 days. Median code health is 7.1 out of 10, but the median hotspot file scores 4.9. And in the median repo, the least-healthy 20% of files hold 60% of the files that needed a bug fix in the last 180 days. The 20 lowest-scoring files were bug-fixed 5.4 times as often as the average file (173 repos with enough fix history).

Those are associations on history, not predictions about any one file. They do say where to look: a small share of files carries most of the change and most of the bug fixes.

When should you refactor?

Refactor at the moment it is cheapest and most useful: right before a feature, during review, and in the files that change most. Waiting for a dedicated "refactoring sprint" is the pattern that most often fails, because the sprint competes with feature work and loses.

  • Before adding a feature. If the new code has no clean place to go, restructure first so the feature becomes a small change. The line usually attributed to Kent Beck is to make the change easy, then make the easy change.
  • During code review. A reviewer who has to read a function three times is telling you it needs a better name or a smaller shape. Fix it in the same pull request, in a separate commit.
  • After a bug fix. The code that hid the bug is usually the code that was hard to read. Leave it clearer than you found it.
  • On hotspots. A code hotspot is a file with high code churn and poor health. Every change there costs the most, so every improvement there is repaid the fastest.
  • When the same code smell shows up a third time. Duplication once is a coincidence. Three copies is a missing helper.

When not to refactor: code that is about to be deleted, code nobody changes and nothing breaks in, and anything you cannot test yet. For the last one, add the test first.

Common refactoring techniques

Most day-to-day refactoring is a handful of moves. Each below is a named transformation from Fowler's catalog (the second edition calls Extract Method "Extract Function", Move Method "Move Function" and Replace Magic Number "Replace Magic Literal"), short enough to apply and verify in minutes.

TechniqueWhat it doesUse it when
Extract MethodLifts a block of lines into a new function with a clear nameA function does several things, or a comment explains a block
RenameGives a variable, function or class a name that says what it isA reader has to open the body to understand the name
Inline MethodReplaces a call with the function's bodyA function only wraps another call and adds nothing
Move Method / Move FieldRelocates code to the class it uses mostA method touches another class's data more than its own
Extract ClassSplits a class into two with separate jobsA class has groups of fields and methods that never meet
Replace Conditional with PolymorphismTurns a long if or switch on a type into subclasses or strategiesThe same switch appears in several places
Replace Magic Number with ConstantNames a literal valueA number's meaning is not obvious
Introduce Parameter ObjectGroups parameters that travel together into one objectSeveral functions take the same four arguments

Scroll the table sideways to see every column.

A small example. This function mixes validation, pricing and formatting:

python
def checkout(cart):
    if not cart.items or cart.user is None:
        raise ValueError("invalid cart")
    total = 0
    for item in cart.items:
        total += item.price * item.qty
    if cart.user.is_member:
        total *= 0.9
    return f"{total:.2f}"

After Extract Method and a rename, the same behavior reads as three steps:

python
def checkout(cart):
    validate(cart)
    return format_total(apply_member_discount(subtotal(cart), cart.user))

Nothing a caller can observe has changed. The tests that passed before still pass, which is the only proof a refactor needs.

How to refactor code safely, step by step

Safe refactoring is small steps with a passing test suite between every one. The test suite is what turns "I think this is the same" into "this is the same". If you skip it, you are rewriting.

  1. Check that tests cover the code. Run them and confirm they pass before you touch anything. A failing suite means you cannot tell a refactor from a regression.
  2. Add a characterization test if nothing covers it. Write a test that records what the code does today, including its odd edges, then refactor against it. It pins behavior without judging it.
  3. Make one change at a time. One extraction, one rename, one move. Run the tests after each.
  4. Commit after each green step. Small commits let you revert one move without losing the rest, and they make the review readable.
  5. Do not mix in behavior changes. If you spot a bug, note it, finish the refactor, and fix the bug in its own commit.
  6. Use the tools you have. IDE refactorings (rename, extract, move) update every reference automatically and are safer than hand edits. Best refactoring tools compared covers the options.

Refactoring with AI tools

AI assistants can refactor code, and the safety rules stay the same. ChatGPT or a coding agent will extract a method or rename a symbol quickly, but it does not know your behavior is unchanged. The test suite does. Give the tool one small, named transformation at a time, run the tests after each, and review the diff as you would a teammate's.

The harder question for an agent is what to refactor. Without data it picks the file in front of it. Ranked targets and a plan with its covering tests give it a specific job.

How to pick where to start

Start where change concentrates and health is low. Refactoring a file nobody edits is real work with no return. Refactoring the file that changes every week and breaks often pays back in days.

A short rule of thumb: rank files by churn, then by health, and read the top ten. Those are your hotspots. Within them, favor changes that are local and mechanical, such as extracting a long function, before changes that ripple, such as moving a class across modules. Git hotspot analysis walks through the method with plain git commands, and refactoring priorities: impact per effort covers how to order the resulting list.

Two other filters help. Check who owns the file: a refactor in code only one person understands needs that person in the review. And check the tests: a hot file with no coverage needs its characterization test before anything else.

How repowise helps with refactoring

repowise turns the health score into named refactoring plans, built from the graph and git history of your repository. It builds them during repowise init and repowise update, with no LLM key and no network needed. Each plan is structured data, not prose advice, and it covers seven types: Extract Class, Extract Method, Extract Helper, Move Method, Break Cycle, Split File and Performance Fix.

bash
uv tool install repowise                          # or pipx / pip install repowise
repowise init                                     # indexes the repo
repowise health --refactoring-targets             # the ranked refactoring queue
repowise health --plan <plan-id>                  # one plan as a prompt an agent applies

A plan names the concrete edit: the line span to lift out and the helper's parameters, the class a method belongs in, or the import edges to cut to break a cycle. It lists the tests closest to the change, with a command that runs them, and when no test reaches the code it asks for a characterization test first. That follows the safety steps above. Each plan also carries a confidence, an effort bucket and a blast radius, so you can pick mechanical, local work first.

Agents reach the same plans through MCP:

python
get_health(only=["fix_first"])                                      # refactorings ranked beside other fixes
get_health(targets=["src/api/server.py"], include=["refactoring"])  # one file
get_health(plan_id="refac...", include=["recipe"])                  # a plan as a recipe an agent applies

repowise does not edit your code by default. Code generation is off until you ask for it, and when you do, the result comes back as a diff for you to review. See the refactoring feature page and the refactoring intelligence docs for the plan types and options.

FAQ

What is refactoring?
Refactoring is restructuring existing code without changing its external behavior. The goal is code that is easier to read, test and change, reached through small transformations such as Extract Method or Rename, each checked by tests that still pass.
Why is refactoring important?
Messy code taxes every later change: more time reading, more risk of breaking something nearby. Refactoring lowers that cost, which makes features faster to add and bugs easier to find. It is the main way teams repay technical debt without stopping feature work.
When should you refactor?
Refactor before adding a feature to a messy area, during code review, after a bug fix, and in the files that change most. Avoid refactoring code that is about to be deleted or that you cannot test yet. Add a test first in that case.
What is the difference between refactoring and rewriting?
Refactoring changes the structure of existing code in small, tested steps and keeps behavior the same. A rewrite replaces the code, usually in one large piece, and tends to change behavior along the way. Refactoring can ship continuously; a rewrite usually cannot.
Does refactoring change behavior?
No. By definition a refactor leaves external behavior unchanged. If the tests that passed before fail after, the change was not a pure refactor. Behavior changes belong in separate commits, such as a bug fix or a new feature.
Can ChatGPT refactor code?
Yes, for small, well-scoped changes such as extracting a function or renaming. Run your tests after each change it makes, because the model cannot prove behavior is unchanged. Give it one named transformation at a time, not "clean this file up".
What is another word for refactoring?
Restructuring or cleaning up code. "Restructuring" is closest. Unlike a rewrite, refactoring is bound by one rule: external behavior does not change.
How do you know what to refactor first?
Start with files that change often and score poorly on health, since each edit there costs the most. Rank by churn, then by health, and check test coverage and ownership before you begin. repowise lists the ranked opportunities with repowise health --refactoring-targets.