Working by Task Type7 minLesson 17 of 60

Refactoring Safely with an Agent

Refactoring is where agents shine and where they bite. Shine, because the work is mechanical and wide. Bite, because a confident wrong change can ripple across many files at once. The fix is structure.

Rules for safe refactors

  1. Have a green test suite first. No tests, no refactor.
  2. Refactor in small, reviewable steps, not one giant sweep.
  3. Keep behavior identical. A refactor that changes behavior is a feature in disguise.
  4. Run the suite after each step and read the diff.
Name the invariant
Tell the agent exactly what must not change: the public API, the output format, the database schema. A clear invariant keeps a wide refactor honest.
Anthropic CookbookFree, open-source recipes and examples for working with Claude, including code tasks.github.com/anthropics
Finished this lesson? Mark it read to track your progress.