Skip to content
← Back to Articles
AI

Refactoring Legacy Code With AI, Safely and in Small Steps

AI can make cleaning up old code much faster, or much riskier. This step-by-step approach uses tests, tiny changes and careful review so you improve legacy code without breaking it.

Paperskeep
Paperskeep
Dec 05, 2026 · 5 min read

Every developer eventually meets The File. It is a few thousand lines long, nobody fully understands it, and everyone is slightly afraid to touch it. It works, mostly, and that is exactly why it is scary.

AI coding tools make it tempting to say "rewrite this cleanly" and let the machine take a swing. Sometimes that even looks like it worked. But a large AI rewrite of code you don't understand is one of the easiest ways to introduce subtle bugs that surface weeks later.

There is a safer way, and AI makes it faster than it used to be.

The golden rule: behaviour first, beauty second

Refactoring means changing the structure of code without changing what it does. With legacy code, the hard part isn't making it prettier. It is being confident that it still behaves the same afterwards.

So before any cleanup, you need a way to detect changes in behaviour. That usually means tests.

Step 1: Understand before you touch

Start by asking your AI assistant to explain, not change:

  • "Explain what this module does, in plain English, section by section."
  • "List every input this function reads, including globals, config and environment variables."
  • "List every side effect: database writes, file writes, network calls, logging."
  • "What parts of this code look like they handle unusual edge cases?"

Check the explanation against the code as you read. Write a short summary in your own words. If you can't explain the code, you're not ready to refactor it.

Step 2: Pin down current behaviour with tests

Legacy code often has few or no tests. That's the first thing to fix, and AI is genuinely helpful here.

Ask for characterisation tests: tests that capture what the code currently does, not what it should do.

Write tests for this function that record its current behaviour,
including odd or surprising results. Don't fix anything.
Cover: normal inputs, empty inputs, boundary values, and invalid inputs.

Run them. If some fail, the AI guessed the behaviour wrong. Adjust the tests to match reality, not the other way around. If you find a genuine bug, note it separately. Fixing bugs and refactoring are two different jobs and should be two different changes.

A refactor without tests is a rewrite with optimism.

Step 3: Pick one small, named refactoring

Big-bang cleanups are where things go wrong. Instead, pick one specific, well-known refactoring at a time:

  • Extract a long block into a well-named function
  • Rename a confusing variable or function
  • Replace a magic number with a named constant
  • Remove clearly dead code (after confirming it's unused)
  • Split one function that does three things into three functions
  • Replace deeply nested if statements with early returns

Then ask the AI for exactly that:

Extract lines 120–175 into a separate function with a descriptive name.
Do not change any behaviour. Do not modify anything else in the file.
Show me the diff.

The phrase "do not modify anything else" matters. AI tools sometimes "helpfully" tidy unrelated code, which makes review harder and adds risk.

Step 4: Review the diff like a sceptic

Read every line of the change. Look specifically for:

  • Conditions that were subtly altered (< becoming <=, an and becoming or)
  • Error handling that was dropped or simplified
  • Changes in the order of operations, especially around side effects
  • Default values that changed
  • New dependencies or imports you didn't ask for

If the diff is too big to review comfortably, the step was too big. Undo and ask for something smaller.

Step 5: Run the tests, then commit

Run your characterisation tests and the rest of the test suite. If everything passes, commit with a clear message like "Extract invoice total calculation into its own function (no behaviour change)".

Small commits give you an easy way back. If something breaks later, you can find the exact step responsible.

Step 6: Repeat

Go back to Step 3 and choose the next small improvement. It can feel slow, but each loop might only take a few minutes with AI help. After a day of this, the file can look dramatically different, and you'll trust it more than before because it's now tested.

When a rewrite really is the answer

Sometimes code is so tangled that incremental cleanup isn't worth it. If you do decide to rewrite:

  • Keep the characterisation tests and make the new version pass them.
  • Run old and new side by side where you can, comparing outputs.
  • Rewrite one part at a time behind a clear boundary, rather than everything at once.

AI can draft a rewrite quickly, but the safety net is still your tests and your review.

Team tips

  • Separate refactoring PRs from feature PRs. Mixed changes are much harder to review.
  • Say "no behaviour change" in the description and mean it.
  • Pair the AI's explanation with a human's history. Someone on the team may know why that strange workaround exists.

The takeaway

AI is a brilliant refactoring partner when you keep it on a short leash. Understand the code first, pin its behaviour down with tests, make one small named change at a time, review every diff carefully and commit often. Your legacy code gets cleaner with each loop, and it keeps working the whole way through.

Enjoyed this piece?

Get the next one in your inbox, every other Friday.

More from Paperskeep