Nguyen Le Phong

Using AI to Refactor Without Changing What the Code Does

Use AI to map side effects, draft characterization tests and compare options, keep mechanical moves in your IDE, and ship refactors in small, verified steps.

A review comment says what everyone already knows: "This function does too much." Nobody argues. Then someone opens the file and remembers why nobody has touched it in months. It validates input, maps fields, writes logs, falls back to a default price and handles one strange case left over from a customer migration years ago. Improving it is clearly possible. The hard part is seeing where the first safe step is.

Engineers look at a dense legacy function together, sketching its flow as blocks to find a safe place to start.
Most of a refactor is figuring out what the code actually does before you move any of it.

That's where AI earns its keep. Refactoring is mostly understanding, and models are good at reading a long function and laying out what's inside. They're also good at producing tidy code that looks right while dropping a behavior somebody depended on. This post is about using the first strength while guarding against the second.

Refactoring has a strict definition

Martin Fowler's definition is worth keeping on a sticky note: refactoring is "a disciplined technique for restructuring an existing body of code," changing its internal structure without changing its external behavior. He describes it as a series of small behavior-preserving transformations. Each one does little, so it's unlikely to go wrong, and the system keeps working after every step (refactoring.com).

That definition tells you what to ask AI for. "Rewrite this cleaner" asks the model to optimize for how the code looks. A better request sets the boundaries and asks for a plan before any code:

Refactor plan only, no code yet.
Function: applyDiscount() in pricing/discount.ts
Goal: split validation, lookup and logging into separate units.
Rules:
- External behavior must not change: same return values,
  same thrown errors, same log lines, same metrics.
- Public signature stays the same.
- List every side effect and every branch you can't explain.
- Propose characterization tests before any change.
- Split the work into small steps; mark each one as
  "mechanical" or "could change behavior".

The last rule matters most. When a step is labeled "could change behavior", it gets its own commit and its own test. Everything else can move fast.

Let AI draw the map first

Many bad refactors go wrong before anyone edits a line. Someone changes the shape of the code without noticing what that shape was protecting. AI is good at drawing the map that prevents this. Ask it to list:

  • inputs, outputs and every side effect (database writes, logs, metrics, events, cache),
  • external calls and what happens when each one fails,
  • places where errors get swallowed or turned into defaults,
  • which parts are pure logic and which touch I/O,
  • branches it can't explain from the code alone.

That last item is gold. A branch the model can't explain is usually a branch with history: a vendor that returns 200 with an error body, a legacy record shape, a customer with a special contract. Take the list to git blame or ask whoever owns the module before you let anything delete it.

A small team maps responsibilities, side effects and possible split points on a whiteboard before touching the code.
The map separates what can move freely from what has to be proven before it moves.

Hyrum's Law explains why those odd details matter: "With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody" (hyrumslaw.com). The exact log line, the order of fields in a JSON response, the error message text. If something outside the function can see it, assume someone reads it.

Pin down current behavior with tests

Before you change legacy code, write characterization tests. Michael Feathers coined the term in Working Effectively with Legacy Code: tests that record what the code does today, whether or not that's what it should do. Mark Seemann's write-up walks through Feathers' recipe. Put the code in a harness, write an assertion you know will fail, let the failure show you the real output, then update the test to expect it (Empirical Characterization Testing).

AI speeds up the boring part. Give it the function and the map, and it'll propose cases you might skip: empty input, duplicate records, a missing permission, a provider timeout, an unexpected status code, the old data shape. It can draft the test files too.

Watch out for one trap. A generated test can pass for the wrong reason: it asserts on a mock, or it compares the output with itself. Seemann's fix works well here. Once a test passes, sabotage the code under test (flip a condition, change a constant) and check that the test fails where you expect, then revert. A test that still passes after sabotage isn't protecting anything. There's more on testing generated code in AI in QA: Generating Tests That Actually Catch Bugs.

Use the right tool for mechanical moves

Once behavior is pinned down, the mechanical work starts: rename a concept everywhere, extract a helper, turn a long if/else chain into a lookup table, move code behind a small interface. A model can draft most of these patches, and it's handy when the change crosses file types your IDE doesn't understand, like SQL strings, config or docs.

For plain renames and extractions inside one language, your IDE's refactoring commands or a codemod are usually the safer pick. They work from the syntax tree and do exactly the same thing every time. A model rewriting a file can change a comparison from < to <=, drop a default value or reorder an error path, and the diff will still look tidy. Any of those changes behavior, which makes it something other than a refactor.

Ask for options, then pick the smallest that helps

Ask for two or three options instead of one answer. For the discount function, that might be:

  • Option A: pull the pure pricing rules into separate functions and leave I/O where it is.
  • Option B: put the vendor call and the logging behind adapters, and keep the business rules in one place.
  • Option C: keep the structure, add characterization tests and clearer names, and come back later.

Seeing them side by side makes the trade-offs obvious. Sometimes option C is the right call this sprint. Tests plus two good names can make the next change safe, and the bigger redesign can wait until you understand the domain better.

Small diffs, then verify like you mean it

Generation makes big edits cheap, and that's exactly the risk. The 2024 DORA report found that as AI adoption increased, delivery throughput dropped by an estimated 1.5% and delivery stability by 7.2%. The authors point back to the basics, small batch sizes and robust testing, and say AI doesn't appear to be a cure-all. A 2,000-line AI refactor in one PR is a big batch, however tidy it looks.

Teammates compare behavior diagrams and test cases around a table before accepting an AI-assisted refactor.
The diff can look perfect. The tests and the behavior checks decide whether it ships.

A checklist that holds up:

  • One kind of change per commit. Mechanical moves in one, anything that might change behavior in its own commit with a test.
  • Run the existing suite and the new characterization tests after every step, not only at the end.
  • Read the diff slowly around comparisons, defaults, error handling and anything serialized.
  • Check what other systems can see: public types, API responses, analytics events, log formats, migrations.
  • Write the PR description for the reviewer: what moved, what stayed the same, and how you checked it.

AI can suggest the verification commands. Deciding whether they're enough is still your call.

Try this week

  • Pick the function your team avoids. Ask AI for a map of its side effects and the branches it can't explain, with no code changes.
  • Write three characterization tests for it, then break the code on purpose and check that each test fails.
  • Do one rename with your IDE's refactor command and compare the result with what a model would produce.
  • Split your next refactor PR into mechanical commits and behavior-touching commits, and ask your reviewer which was easier to read.

If you want AI on the first draft of the boring parts, Let AI Write the Boring First Draft covers where that works and where it doesn't.

What did you think?

Frequently asked questions

Can AI refactor code safely?
It can help a lot, as long as behavior is pinned down first. Use AI to map side effects and draft characterization tests, make changes in small steps, and run the tests after each one. Treat any change to a comparison, default value or error path as a behavior change that needs its own commit and test.
What is a characterization test?
A test that records what code does today, whether or not that's the intended behavior. Michael Feathers coined the term in Working Effectively with Legacy Code. You write an assertion you expect to fail, let the failure show the real output, then update the test to expect it, so you have a safety net before changing legacy code.
Should I use AI or my IDE for renames and extractions?
For plain renames and extractions within one language, IDE refactoring commands or codemods are usually safer because they work from the syntax tree and behave the same every time. AI is more useful for understanding the code, proposing a plan and handling changes that cross file types like SQL strings, config and docs.
How do I review an AI-assisted refactor?
Ask for small commits that separate mechanical moves from anything that might change behavior. Read the diff slowly around comparisons, defaults, error handling and serialized data, check public types, API responses, events and log formats, and make sure the characterization tests fail when the code is deliberately broken.