---
name: Refactoring
description: Improve structure without changing behavior.
---
# Refactoring

Refactor only under a green test suite, in small steps, each step leaving the code working. Large speculative rewrites mix behavior change with structure change and become impossible to review or roll back.

## Discipline
- **Never mix refactor and feature in one commit.** A reviewer (or future you) must be able to read "behavior unchanged" without doubt.
- **Take steps small enough to describe.** "Extract function", "rename", "inline variable". Each compiles and passes tests. Commit after each.
- **Let pain drive it.** Refactor the third copy of a pattern (rule of three), not the first. Refactor the code you're about to change anyway, not code "for later".
- **Preserve behavior first, improve names second.** A correct-but-ugly function is recoverable; a renamed-but-broken one is a live bug.

## Catalog moves (apply singly)
Extract Function, Inline Function, Extract Variable, Rename, Move Function, Replace Conditional with Polymorphism, Replace Magic Literal with Named Constant.