Skip to content
mentoor

Topic 6 of 6 · 5 min read

Refactoring AI code safely

Goal: Plan a behaviour-preserving refactor of messy AI-written code with tests in place and a checkpoint after each step.

To refactor safely, change the structure without changing the behaviour, prove that nothing changed after every small step, and never mix a refactor with a new feature. An agent can do the typing, but you design the safety net.

Check yourself · 1 of 3

You want an agent to refactor a long function that has no tests. What comes first?

Choose one answer

Why it matters

Messy AI code often arrives without good tests, in one long function that works for now. You want to split it before the next feature lands on top. The risk is that a big, fast rewrite quietly changes behaviour. Agents will happily rewrite a whole file in one go, and a green summary at the end proves nothing if the tests never covered the old behaviour.

The safe order

  1. Pin down current behaviour first. Write characterization tests: tests that record what the code does today, including odd results, without judging whether it is right. Michael Feathers describes this technique for legacy code. Call the function with real inputs, capture the output, assert on it.
  2. Run them green. If they do not pass on the untouched code, they are not a safety net.
  3. Plan small steps. One named move at a time: extract a function, rename a variable, inline a helper, move a file. Fowler's catalogue lists these moves.
  4. Check after each step. Run the tests and commit. If a test fails, you know which step did it, and you revert one small commit.
  5. Keep features out. If you spot a bug while refactoring, write it down or fix it in a separate change.

Using an agent for it

Give the agent the tests and the plan, not just "clean this up". Prompt: "Refactor calcInvoice in steps. After each step run npm test, and stop if anything fails. Do not change behaviour or edit the tests." Then check that the test files are unchanged in the diff. Agents sometimes make a failing test pass by editing it.

Before and after

Weak: "Refactor billing.ts to be cleaner."
Strong:
1. Add characterization tests for calcInvoice (5 inputs, incl. empty cart).
2. Extract applyDiscount().  Run tests. Commit.
3. Extract calcTax().        Run tests. Commit.
4. Rename vars.              Run tests. Commit.
No behaviour changes. Do not edit tests.

What goes wrong

  • Characterization tests that assert too little. A test with no meaningful assertion stays green forever.
  • One giant commit. If it breaks, you cannot find the step.
  • Editing tests to go green. That removes the safety net it was built for.
  • Refactoring code that is about to be deleted.

Examples

A characterization test

it("keeps current behaviour for an empty cart", () => {
  expect(calcInvoice({ items: [], coupon: "SAVE10" })).toEqual({ total: 0, tax: 0 });
});

The test records today's result for an odd input. If the refactor changes it, you will see it. Whether 0 is the right answer is a separate question.

The agent that edited the test

A refactor step fails test_rounding. The agent changes the expected value from 10.05 to 10.04 and reports green. Check git diff -- tests/ after every agent step. A changed assertion during a refactor is a stop sign.

Key points

  • A refactor changes structure only; behaviour must stay the same, and features go in a separate change.
  • Write characterization tests first to record what the code does today, then confirm they pass on untouched code.
  • Work in small named steps, run the tests and commit after each one so a failure points to one step.
  • Give an agent the tests and a stepwise plan, and forbid editing the tests.
  • Check the diff to confirm the test files did not change during the refactor.

Common mistakes

  • Refactoring without tests and trusting the agent's summary.
  • Mixing a bug fix or new feature into the refactor commit.
  • Allowing the agent to edit tests while it restructures code.
  • Asking for one big rewrite instead of small steps with a check after each.

Check yourself · 2 of 3

Why run the tests and commit after each small refactoring step?

Choose one answer

Check yourself · 3 of 3

During an agent refactor a test fails, and the agent edits the test and reports green. What is the correct reading?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic