Skip to content

How to refactor with a coding agent and prove the behaviour did not change

A refactor must not change behaviour. Pin the current behaviour with tests first, make small steps, run the suite after each, and review the diff for logic.

Published by Contextingo.

Refactoring changes the structure of code and leaves its behaviour alone. Agents are good at moving code and not good at knowing what must stay the same. You supply that.

Steps

  1. Check that tests cover the code you will touch. If they do not, ask for characterization tests that record what the code does today, correct or not.
  2. Run them and commit them separately.
  3. Refactor in small steps, each one a commit that keeps the suite green.
  4. Do not mix a refactor with a feature or a bug fix.
  5. Review the diff for logic changes hiding inside moves. A renamed function with a changed condition is the classic case.

What to ask the agent for

  • A plan with the steps in order, approved before any edit.
  • A statement of what will not change: public interfaces, data formats, error messages.
  • A summary at the end listing any behaviour it noticed and left alone.

Signs of trouble

  • Tests were edited to pass.
  • The diff is much larger than the plan.
  • Files outside the area changed.

Related: small pull requests for agent work.

Questions

Good to know.

What are characterization tests?

Tests that record what the code does now, so you can see if a change alters it.

Can I refactor without tests?

It is riskier. Write the pinning tests first, even rough ones.

Nothing learned is lost. Nothing unchecked is done.