Characterisation Tests and Safe Refactoring with AI Agents
Pin down behaviour, then change structure.
Hello. In this lesson I will take you through 3 ideas, one at a time.
Why it matters: Pin down behaviour, then change structure. After each idea I will ask you one quick question.
In this lessonFollows you as you read
Tests that record what is
The short version: Before changing old code, write tests that record what it does now, right or wrong.
Before changing old code, write tests that record what it does now, right or wrong. These characterisation tests are a safety net: if a refactor changes behaviour, a test fails.
Agents are well suited to this. Give one a function or screen and ask for tests of its current behaviour across normal and edge inputs.
What do characterisation tests record?
Small steps
The short version: Refactor in steps that each leave the app working: rename, extract, move, replace.
Refactor in steps that each leave the app working: rename, extract, move, replace. One kind of change per commit. Run the tests after each.
Give the agent one step at a time with the tests as the judge. Large mixed changes are where behaviour silently shifts.
Why separate behaviour fixes from refactoring?
When behaviour is wrong
The short version: Sometimes the tests reveal a bug users rely on.
Sometimes the tests reveal a bug users rely on. Do not fix it inside a refactor. Record it, decide separately, and change it as its own release with its own notes.
Structure changes and behaviour changes should never travel together.
- Record current behaviour before changing structure
- One kind of change per commit
- Tests judge every step
- Fix behaviour separately from refactoring
Pick one messy function. List eight inputs you would use to characterise it and the first three refactoring steps.
Mark it complete to track your progress on this device.