Claude · Coding

Refactoring

Restructure code one named move at a time, starting with characterization tests when the code has none.

Claude for refactoring

The order that keeps a refactor safe

Work in this order. First make sure tests exist and can actually fail. Then rename, so the code says what it does. Then extract one piece at a time, committing after each. Each stage makes the next one easier and keeps a failure easy to trace. If your tests go red, the only suspect is the move you just made. Keep bug fixes out, and have Claude list any it notices so you can fix them later as separate changes.

Claude Code's undo has limits

Commit before each move, and don't rely on /rewind alone. Anthropic's docs say it doesn't restore a file that only a Bash command changed, which matters if Claude runs sed across your code. Edits from most subagents aren't restored either. Be careful with /simplify too, since it applies cleanups and doesn't look for correctness bugs. For bugs, use /code-review on your commit range. And keep routine refactors at high effort or below. Anthropic's Sonnet 5.5 guide says the model may make related fixes on its own at xhigh and max.

Frequently asked
How do I refactor safely with Claude?

Ask for one named move at a time, such as extract or rename, with behavior unchanged. Run the tests and commit after each one. Tell Claude not to edit tests, and to list any bugs it notices instead of fixing them.

How do I refactor code that has no tests?

Have Claude write characterization tests that record what the code does today, including odd behavior. Then confirm they fail when the code is broken on purpose. Only after that should you start changing the structure.

Why is "clean this up" a bad refactoring prompt?

It sets no boundary, so Claude has to guess what you'd accept, and behavior changes can slip in with structure changes. Name the move and the scope instead, and say that behavior must stay exactly the same.

Can I undo a Claude Code refactor?

Often, with /rewind or by pressing Esc twice on an empty prompt. It doesn't cover files changed only by Bash commands, and most subagent edits aren't restored. Anthropic says it works alongside git rather than replacing it, so commit first.