Refactoring
Restructure existing code safely without changing behaviour.
Refactor in named, safe steps
The risk in refactoring is changing behaviour while trying only to change structure. Reduce it by asking Claude for named, small steps rather than one sweeping rewrite: 'extract this into a function, behaviour identical', then 'inline that duplicate', then 'rename for clarity'. Each step is easy to review and easy to revert. Vague requests like 'clean this up' invite exactly the silent behaviour changes you want to avoid. Precise, incremental moves keep the refactor honest and the diff readable.
Protect behaviour with tests
Before a meaningful refactor, get the behaviour under test — ask Claude to write tests that capture what the code currently does, then refactor against them. If the tests stay green, the behaviour held; if one breaks, you have caught a regression the moment it happened. This is what makes AI-assisted refactoring safe at scale: you are not trusting that the change preserved behaviour, you are verifying it. Keep each step small enough that a red test points clearly at the cause.
How do I refactor safely with Claude?
Ask for small, named steps that preserve behaviour — extract, inline, rename — rather than one sweeping rewrite. Each step is easy to review and revert, keeping the refactor honest.
How do I stop refactoring from changing behaviour?
Get the behaviour under test first, then refactor against those tests. Green tests confirm behaviour held; a red one catches a regression immediately.
Why is 'clean this up' a bad refactoring prompt?
It is vague enough to invite silent behaviour changes. Precise, incremental instructions keep the diff readable and the behaviour intact.