How to Refactor AI-Generated Code Safely

Generated code usually works. Its problems are duplicated logic, abandoned attempts and no structure. You can fix those a step at a time, as long as you protect what already works.

How to Refactor AI-Generated Code Safely — Troiana insight cover

In short

To refactor AI-generated code safely, first put it under version control, and add end-to-end tests around key journeys. Then remove dead code, consolidate duplicated logic, separate concerns and improve names in small, reviewed steps. Fix security and data problems before cosmetic ones. Agents can do much of the work if you give them narrow tasks and read the diffs. Stop when changes stop paying off.

What's usually wrong

Generated code has recognisable patterns, particularly after many rounds of prompting:

  • Duplication. The same logic appears in several components, because each prompt solved it afresh.
  • Dead code. Abandoned attempts and unused files remain.
  • Giant components. One file handles data, logic and display.
  • Inconsistent patterns. Three ways of fetching data, and two ways of handling errors.
  • Weak error handling. Happy paths work, while failures do nothing visible.
  • Too many dependencies, often added for a single function.
  • No tests.

These make each change slower and riskier. They also mislead AI tools, which copy whichever pattern they find. See the real cost of technical debt and when you should refactor code.

Before you touch anything

  1. Check that it's worth it. Audit first. If the data model is wrong, refactoring around it may be wasted. See how to fix a vibe-coded app.
  2. Fix urgent security problems now, rather than waiting for a clean-up. See the security checklist.
  3. Get it into Git, and tag the current version, so you can always go back.
  4. Add safety tests. Write end-to-end tests for your critical journeys. They check behaviour from the outside, so they don't need changing when you reorganise the code. See how to test a vibe-coded app.
  5. Stop feature work on the areas being refactored, or merges will become painful.

Tests are what make refactoring possible. Without them, you can't tell whether your change preserved behaviour, and that's the definition of a refactor.

A safe order of work

Step 1: remove what's dead. Delete unused files, components, dependencies and environment variables. This is low-risk and high-value, as there's less for anyone to read, and fewer bad patterns for an AI to copy. Tools such as knip (JavaScript) or your IDE can find a lot of it. Run your tests after each batch.

Step 2: turn on stricter checks. Add a linter, a formatter and TypeScript strict mode if you can. You may get many errors, so fix them gradually. These tools catch real bugs, and give agents immediate feedback. See should you use TypeScript?

Step 3: pick one pattern for each job. Decide how you fetch data, handle errors and manage forms. Write it down in your project instructions. Convert the code gradually, starting where you're making changes anyway.

Step 4: consolidate duplication. Move repeated logic into shared functions. Prioritise anything that touches money, permissions or dates, since duplicated business rules drift apart and cause real bugs. Don't try to unify things that only look similar. Some duplication is fine.

Step 5: separate concerns. Move business logic out of the interface, and data access into one place. That also makes it far easier to replace a platform-specific SDK later. See modern front-end architecture.

Step 6: improve names and split large files. Clear names help both humans and AI tools. Rename before moving, to keep each change easy to review.

Step 7: add tests underneath, as logic becomes separate enough to test directly.

With tests already in place
Remove what's deadLow risk
Stricter checksLinter, strict mode
One pattern per jobWritten down
ConsolidateMoney, permissions, dates first
Separate concernsLogic out of the interface
The first five steps. Each one makes the next safer, and leaves less bad code for an AI tool to copy.

Keep changes small

A refactor should change structure, not behaviour. Keep it that way:

  • One concern per change. “Extract price calculation”, not “clean up the checkout”.
  • Don't mix refactoring with new features or bug fixes. If you find a bug, note it and fix it separately.
  • Deploy often. Small releases are much easier to roll back. See ship small, ship often.
  • Review every diff. See how to do a code review.

Using agents for the work

Coding agents are good at mechanical refactors, as long as you constrain them. A task like this works well:

Extract the price calculation from CheckoutPage.tsx into
src/lib/pricing.ts. Do not change behaviour.
Update the two call sites. Run the tests and the type check.
Show me the diff. Don't touch any other files.

Tips:

  • Ask for a plan first, and approve it. See what context engineering is.
  • Use a fresh session for each task, so that stale context doesn't confuse it.
  • Forbid changes to tests, unless you've agreed to them. An agent under pressure may weaken a test in order to pass it.
  • Use a separate review. A subagent or a second tool can review the diff with fresh eyes.
  • Be suspicious of large diffs. “Refactor this codebase” is a recipe for a change that nobody can check.

Warning signs that a refactor is going wrong

  • Tests are being edited to make them pass
  • The diff touches far more files than you expected
  • New dependencies have appeared
  • Behaviour changes “just slightly”
  • It's been weeks since anything shipped
  • The new abstraction needs more code than the duplication it replaced

If you see these, stop and go back to the last good point. Reverting is cheap. See the case for boring technology.

Data model changes

If the database needs changing, treat that as its own project. Change it in stages: add the new structure, write to both, migrate the data, then remove the old. Back up first, and test the restore. See how to write a safe database migration.

When to stop

You don't need perfect code. You need code that's safe to change. Stop when:

  • Common changes have become quick
  • Bugs are staying fixed
  • A new developer or agent can find their way around
  • More clean-up wouldn't change what your customers experience

Leave the rest, and improve things when you next work in that area. Keep an honest list of what's left. And prevent the mess from coming back, with tests in CI, written conventions and a review step. See what harness engineering is.

If you'd like experienced help with an AI-built codebase, book a call.

Common questions

Should I refactor or rewrite AI-generated code?

Usually refactor, if the data model is sound and the app has real users. A rewrite throws away edge cases that the code already handles. Consider rebuilding if the data model is wrong, there are no users, or the platform blocks you.

Can I use AI to refactor AI-generated code?

Yes, and it's very effective for mechanical changes. Give it narrow tasks, ask for a plan first, forbid changes to tests, and read every diff. Avoid broad requests like refactor everything, because the results can't be reviewed properly.

What should I refactor first?

Fix security problems first, and add tests around your key journeys. Then remove dead code and consolidate logic that touches money, permissions or dates. Save names and structure for later, unless they're blocking your other work.

How do I refactor without breaking things?

Write end-to-end tests first, change one thing at a time, keep behaviour the same, and deploy often in small steps. Keep refactors separate from features. Use version control, so that you can quickly go back to the last good state.

Have something worth building right?