StoicBuilder

HandbookXV the PantheonRefactoring safely

XVthe Pantheon, Design the system

Refactoring safely

1 min readUpdated 28 November

In plain words

Refactoring changes how code is organised without changing its behaviour, done safely in small steps, each covered by tests and shipped on its own, so any mistake is small and quick to trace.

Where you see it

Harbor's 1,800-line invoice module needs splitting before new tax rules arrive. Instead of one big rewrite, the team adds characterisation tests that pin down today's outputs, then moves one function at a time, each in its own pull request, with the tests green after every step.

modules/billing/invoice.test.tsserver
test("invoice totals match today's behaviour", () => { for (const fixture of loadFixtures("invoices/2026-11")) { expect(calculateInvoice(fixture.input)).toEqual(fixture.expectedOutput); }});
Real past inputs and today's outputs, captured before you touch anything. If a refactor changes one number, this fails.

What goes wrong

  1. Refactoring and changing behaviour in one go

    When a pull request both moves code and changes the tax rule, a wrong total could come from either. Refactor first and merge, then change behaviour in a separate pull request.

  2. No tests to catch the slip

    Without tests that cover current behaviour, a refactor is a hopeful rewrite. Write characterisation tests first, even for behaviour that looks wrong, and fix that later on purpose.

  3. Letting the agent tidy everything it touches

    Asked to fix one bug, an agent may rename and reorganise a dozen files, and the diff becomes impossible to review. Ask for refactors as separate, named tasks with the scope stated.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Refactor this module without changing its behaviour. First write characterisation tests that capture current outputs for real inputs, then make one structural change per commit, such as extracting a function or moving a file, running the tests after each. Don't fix bugs or change behaviour in this work; list any you find for later.

Quick check

Sign in to earn +10 XP for it

Your agent's pull request refactors Harbor's invoice module and also changes how discounts round. A total is now wrong. What should have been done differently?

Got a prompt that touches refactoring safely?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.