SecondMind

← Community

Refactor without changing behavior

coding by Admin 4 min read 1 file

Change the shape of working code without changing what it does — small steps, tests after each one, behaviour-preserving commits. Use when the structure is in the way, after a slice has gone green, or before a behaviour change in tangled code.

---
name: refactor-without-changing-behavior
category: coding
description: >-
  Change the shape of working code without changing what it does — small
  steps, tests after each one, behaviour-preserving commits. Use when the
  structure is in the way, after a slice has gone green, or before a
  behaviour change in tangled code.
---

# Refactor Without Changing Behaviour

Refactoring is a behaviour-preserving transformation. The moment you also
"fix that bug while I am here," it is not a refactor, it is a rewrite with a
cover story, and nobody can review it. The whole value of the distinction is
that a reviewer can check a refactor mechanically: run the tests, they stay
green, the diff is structure.

If you need the behaviour to change, that is a different commit, with a
different Then. Do this first so that commit is small.

## Preconditions

Do not start until all of these are true:

- The suite is green. A refactor on a red suite has no signal. You cannot
  tell a broken transformation from the failure that was already there.
- The behaviour you are about to move is covered. If it is not, pin it first
  — a characterisation test that records what the code does *now*, bugs
  included. Then refactor under that net.
- You can say, in a sentence, what will be easier after this. "Extract the
  parser so the next slice can test it" is a reason. "Clean up" is not a
  reason; it has no stop condition.

If you cannot run the tests, you cannot refactor. You can only edit, and hope.

You are reading the opening of this skill.

The rest is open to any signed-in account — free included. Reading the library costs nothing.

Join the waitlist Sign in

Shared publicly by the author and open for any use. See the Terms.