How to refactor safely in code you don't fully understand
Characterisation tests, small steps, parallel implementations and feature flags: techniques for changing structure without changing behaviour in unfamiliar code.
Refactoring means changing a codebase's structure without changing its behaviour. In code you know well, that's routine. In code you don't, the risk is that you change behaviour you didn't know existed. These techniques keep the risk low.
Know exactly what you're preserving
Before touching anything, write down the behaviour of the code you'll change: inputs, outputs, side effects, errors. If you can't describe it, you're not ready to refactor it. Trace the code and its callers first. See estimating the impact of a change.
Write characterisation tests
Characterisation tests record what code does now, not what it should do. Call the function with a range of realistic inputs and assert the current outputs, including odd ones. If a later step changes any output, a test fails and you know you changed behaviour.
Snapshot tests can be useful here, as a temporary safety net for complex outputs.
Take small steps
Each step should be small enough to review and revert on its own:
- Rename a variable.
- Extract a function.
- Move a function to a new file.
- Replace a conditional with a lookup.
Run tests after each step. Commit often. If something breaks, the last commit tells you exactly what caused it.
Separate refactoring from behaviour changes
Never mix the two in one commit or pull request. If you notice a bug while refactoring, write it down and fix it separately. Mixed changes make it impossible for reviewers, and for you later, to tell which change caused which effect.
Use parallel implementations for risky changes
For a significant rewrite:
- Build the new implementation next to the old one.
- Run both in production, using the old result and comparing the new one, logging differences.
- Once differences are understood and fixed, switch to the new one behind a flag.
- Remove the old implementation.
This is sometimes called a "parallel run" or "branch by abstraction", and it's how large, risky refactors are done safely.
Lean on tools
- Your editor's rename and move refactorings update references automatically and correctly.
- TypeScript catches many broken call sites; tightening types before refactoring increases that safety.
- Codemods (scripts that transform code) make large mechanical changes consistent.
Watch for hidden callers
Dynamic imports, string-based lookups, framework conventions, external API consumers and reflection all call code without visible references. Search for the names as strings, not just as identifiers.
Understand before you move
Ask RepoGrasp "what does syncInventory do, who calls it, and what side effects does it have?" before extracting or moving it. The cited answer gives you the behaviour to preserve and the callers to check.
Get a cited summary before your next refactor.