Refactor Code Safely with AI
- The official refactoring recipe has four steps: find the legacy code, ask for recommendations, apply the changes “while maintaining the same behavior”, then run the tests. Its tips include doing refactoring “in small, testable increments”.
- The best-practices page says Claude stops when the work looks done, so give it a check that comes back pass or fail (a test file, a build exit code, a linter) and ask for the command it ran and its output as evidence.
- For changes you want to review before they touch disk, the common-workflows page suggests plan mode: Claude reads files and proposes a plan but makes no edits until you approve. Start it with
claude --permission-mode planor press Shift+Tab until the status bar shows plan mode. - To undo,
/rewindrolls back files Claude edited with its own tools. The checkpointing page says checkpoints are session-level recovery and to keep using Git for commits and long-term history. - We read three official pages on 2026-11-04. We did not run Claude Code for this tutorial. The prompts, the “tests first” order and the Git commands are our own advice or standard Git, not official rules.
What you’ll be able to do after this tutorial
Section titled “What you’ll be able to do after this tutorial”- Explain what refactoring is and why a passing test run before you start matters.
- Ask Claude for a plan, read it, and approve only the part you want.
- Work in small steps, with a test run and a commit after each one.
- Go back to a known good state with
/rewindor Git when a step goes wrong.
Concepts to know first
Section titled “Concepts to know first”Refactoring means changing how code is organized (names, structure, duplicated parts) without changing what it does. That is why tests matter: if the same tests pass before and after, you have some evidence that behavior did not change. A test only covers what it checks, so passing tests are evidence, not proof. 1. Getting started with Claude Code shows how to start. For the commit and branch habits used here, see Coding 17. For finding the cause of a failing test, see Coding 16, and for having the finished change reviewed, Coding 15.
Step-by-step guide
Section titled “Step-by-step guide”-
Make a safe starting point
In your own terminal, create a branch and confirm that your working tree is clean:
Terminal window git switch -c refactor-utilsgit statusCommit or stash anything unfinished first, so every later change in the diff comes from this refactor.
-
Run the tests before changing anything
The best-practices page explains why a check matters: with nothing to run, “looks done” is all Claude has, and you become the test suite. Run your project’s test command yourself (for example
npm test; use whatever your project uses) and note the result. If the tests already fail, fix that first or write down which ones fail, so you do not blame the refactor later. If your repo has no tests, ask Claude to add some for the code you will touch, as a separate step and commit. The common-workflows page has a “Work with tests” recipe for this, which we did not follow in detail. -
Find what to refactor
The official recipe starts with a question, not an edit, for example “find deprecated API usage in our codebase”. Try a read-only prompt of your own:
Copy and paste this promptLook at utils.js. Do not edit anything. List the functions that are long, repeated or hard to read, and for each say what is wrong in one sentence. Rank them by how risky they would be to change, safest first. Say which of them have tests and which do not.
-
Ask for a plan before edits
For changes you want to review before they touch disk, the common-workflows page points to plan mode. Start with
claude --permission-mode plan, or press Shift+Tab during a session until the status bar shows plan mode. In that mode Claude reads files and proposes a plan, and makes no edits until you approve. A prompt to use:Copy and paste this promptPropose a plan to refactor the safest function first. Break it into steps that each change one thing and can be tested alone. For each step, say which files change and how I can check that behavior stayed the same. Do not include any behavior change or new feature.
Read the plan. Cross out steps you do not want. The docs mention that you can edit the plan in your text editor; we did not try this.
-
Do one small step
The official tips say to do refactoring in small, testable increments. Approve only the first step, and ask for the check in the same prompt:
Copy and paste this promptDo step 1 only: extract the repeated date formatting into one helper function and use it where it was repeated. Keep the behavior the same. Then run the tests and show me the command you ran and its output. If a test fails, stop and tell me instead of changing the test.
Asking for “the command it ran and its output” follows the best-practices advice to ask for evidence. Then run the tests yourself too.
-
Read the diff, then commit
In your own terminal:
Terminal window git diff # every changed linegit status # any file you did not expectCheck that no test file changed unless you asked for it. If it looks right, commit with a message that says it is a refactor with no behavior change, for example
git commit -am "Extract date formatting helper". Using-amonly stages files Git already tracks; usegit add <files>for new files. Then go back to step 5 for the next step. -
Review the whole change
When the plan is finished, run the tests once more, then ask for a fresh look. The best-practices page says
/code-reviewreviews the diff in a fresh subagent that never saw your conversation. You can also write your own review prompt:Copy and paste this promptCompare this branch with main. List every place where behavior might have changed, even slightly, such as different error handling, ordering, default values or rounding. Do not edit anything.
-
Go back when a step goes wrong
Pick the layer that matches the damage:
Situation What to use Claude is heading the wrong way Escto stop itClaude’s file edits in this session were wrong /rewind(orEsctwice on an empty prompt) to roll back code, conversation or bothA file was changed only by a Bash command Checkpoints do not track it; use Git, such as git restore <file>The step is committed but wrong git revert <commit>adds a new commit that undoes it (standard Git)Everything on the branch is wrong Switch back to mainand delete the branch (standard Git); nothing else was touchedThe checkpointing page says checkpoints are for quick session-level recovery and that Git remains the tool for commits and long-term history.
Quick reference
Section titled “Quick reference”| Task | Command or place |
|---|---|
| New branch | git switch -c <name> |
| Plan mode at start | claude --permission-mode plan |
| Plan mode in a session | Shift+Tab until the status bar shows plan mode |
| Ask for proof | “show me the command you ran and its output” |
| Roll back Claude’s edits | /rewind or Esc twice on an empty prompt |
| Review the diff | /code-review |
| Undo a commit safely | git revert <commit> |
Common problems
Section titled “Common problems”Tests fail after a step
Section titled “Tests fail after a step”- Cause: The step changed behavior, or the tests were already failing.
- Fix: Compare with your note from step 2. If the step caused it, roll it back with
/rewindor Git and ask for a smaller step. Do not accept a change to the test unless the old expectation was truly wrong.
Claude changed the tests to make them pass
Section titled “Claude changed the tests to make them pass”- Cause: It treated the failing test as the problem.
- Fix: Say in the prompt that tests must not be edited unless you agree. Check
git difffor test files and restore them withgit restore <file>.
The diff is far bigger than I expected
Section titled “The diff is far bigger than I expected”- Cause: The step covered too much, or formatting changes were mixed in.
- Fix: Roll back and ask for one change at a time. Keep formatting-only changes in their own commit.
/rewind did not undo a change
Section titled “/rewind did not undo a change”- Cause: The file was changed only by a Bash command, which checkpoints do not track.
- Fix: Use Git:
git restore <file>, or go back to the last commit.
There are no tests at all
Section titled “There are no tests at all”- Cause: Nothing can confirm that behavior stayed the same.
- Fix: Add a few tests for the code you will change first, in a separate commit, or refactor only very small, obvious pieces and check them by hand.
Practical tips
Section titled “Practical tips”- Practice in a throwaway repository before touching real work.
- One idea per commit makes
git reverteasy. - A green test run is evidence, not a guarantee. Check anything the tests do not cover by hand.
- Do not refactor and add features in the same step.
- Re-check commands and keys against the official pages, since Claude Code changes often.
Next tutorials
Section titled “Next tutorials”Sources
Last verified: Nov 16, 2026
- Common workflows (Refactor code, Plan before editing) code.claude.com
- Best practices for Claude Code (Give Claude a check to run) code.claude.com
- Checkpointing code.claude.com
Prices, limits, and menu names change often. Before making an important decision, check the official pages above for the latest details.
Finished this tutorial?
Progress is saved only in this browser and never sent anywhere.