Lesson 3 of 4 · 30 min

Characterisation Tests and Safe Refactoring with AI Agents

Pin down behaviour, then change structure.

XDQ Tutor · AI guide

Hello. In this lesson I will take you through 3 ideas, one at a time.

  1. Tests that record what is
  2. Small steps
  3. When behaviour is wrong

Why it matters: Pin down behaviour, then change structure. After each idea I will ask you one quick question.

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.

Quick check

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.

Quick check

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.

Key takeaways
  • Record current behaviour before changing structure
  • One kind of change per commit
  • Tests judge every step
  • Fix behaviour separately from refactoring
Try it

Pick one messy function. List eight inputs you would use to characterise it and the first three refactoring steps.

That is the lesson.
Mark it complete to track your progress on this device.
← PreviousApp Rewrite vs Refactor: How to DecideNext lesson →Adding Features and Relaunching an Existing App