Refactoring safely

10 min read text
Course contents (20 lessons)
  1. Meet Claude Code
  2. What Claude Code is and how it differs from a chat window
  3. Installing Claude Code and signing in
  4. Your first session: explore, ask, change
  5. Asking well and staying in control
  6. Asking for changes: context, goal, constraints and acceptance criteria
  7. Reading and approving edits
  8. Permission modes: how much freedom to give
  9. Project memory and slash commands
  10. CLAUDE.md: teaching the tool about your project
  11. Slash commands and custom commands
  12. Everyday coding workflows
  13. The plan-first workflow
  14. Understanding unfamiliar code
  15. Debugging with Claude Code
  16. Refactoring safely
  17. Writing tests with Claude Code
  18. Git, small changes, cost and security
  19. Git workflows: branches, commits and pull request descriptions
  20. Keeping changes small and reviewable
  21. Context and cost awareness
  22. Security habits: secrets, commands and untrusted input
  23. Extending the tool, teamwork and a final project
  24. Hooks and MCP servers explained
  25. Team practices for AI-assisted coding
  26. Final project: building a small app step by step

What a refactor is

Refactoring means changing the structure of code without changing what it does. That definition is the whole safety rule: if the behaviour changes, it is not a refactor, it is a change. Tools like Claude Code are good at the mechanical parts of refactoring, such as renaming across many files and extracting methods. They are less reliable at knowing what behaviour must be kept, so you supply that.

Step 1: make sure there are tests

Before you restructure anything, check that tests exist and pass. If they do not, write them first.

I want to refactor the pricing logic in PricingService. First, look at the existing tests for it. List which behaviours are covered and which are not. Do not edit anything.

If coverage is thin, add characterisation tests: tests that record what the code does today, even if you are not sure it is right.

Write characterisation tests for PricingService.CalculatePrice. Cover normal orders, zero quantity, negative quantity, a missing discount code, an expired code and a very large quantity. Record the current behaviour, even if it looks odd, and add a comment on any case that looks like a bug. Do not change the production code.

Why it works

These tests are a net under the refactor. Once they pass, any later failure tells you that the refactor changed behaviour. The instruction to comment on odd behaviour, rather than fix it, keeps the refactor separate from bug fixes, which is a rule worth following.

Step 2: describe the target

Refactor CalculatePrice, which is 180 lines long, into smaller private methods: one for base price, one for discounts, one for tax and one for rounding. Behaviour must not change. Do not rename public methods. Do not touch other classes. Run the pricing tests after each extraction and stop if any fail.

The boundaries are clear: what to split, what to leave alone, and when to stop. "Run the tests after each extraction" turns a big risky change into a series of checked small ones.

Step 3: mechanical changes at scale

Large renames, moving files and updating imports are tedious and error-prone for people. The tool does them well, and you can check them with the compiler and tests.

Rename the class CustomerRecord to Customer everywhere in the solution, including tests, comments and config files that refer to it by name. Do not rename the database table or the JSON property names. Build and run all tests when finished.

The sentence about the table and JSON names matters. Those are external contracts, and a blind rename can break stored data or clients.

Check that behaviour is unchanged

  • All tests pass, and no tests were deleted or loosened. Look at the diff of the test files.
  • The public interface is unchanged, if that was the aim.
  • Build warnings did not increase.
  • For risky areas, run both old and new versions on the same real data and compare the output.
git diff --stat
git diff -- tests/

The second command shows only changes in the tests folder. A refactor should normally change tests very little. If many assertions changed, find out why.

Keep refactors separate from features

Do not mix them in one commit. A reviewer reading a pure refactor can skim, knowing that behaviour should not change. A reviewer reading a mix has to check everything closely. Commit the refactor first, then do the feature on top.

Know when not to refactor

Ask the tool for a recommendation before you start:

Is this refactor worth doing now? List the benefit, the risk and the files affected. Suggest the smallest version that would give most of the benefit.

Sometimes the answer is that the code is ugly but stable and rarely touched, and the best choice is to leave it.

The common mistake

The common mistake is a "while I am here" refactor with tool help. It is easy for the tool to also tidy the next file, and the next. The diff grows, review quality drops and one subtle change slips through. State "only this file" in the prompt, and stick to it.

Try it yourself

Pick a long function in your project. Ask for coverage analysis, then write characterisation tests, then extract two smaller functions with tests run after each step. Commit each step separately. Review the final diff for anything that changed in a test file.

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account