Refactoring with AI assistants: a safe workflow
AI assistants can untangle a long function in seconds, and introduce a subtle bug just as fast. This workflow keeps the speed and puts tests and review in charge.
Old code is expensive to change. A 200 line function with nested conditions takes an afternoon to understand and another to restructure safely. AI coding assistants are good at exactly this kind of mechanical restructuring. They are also confident when they are wrong, so the workflow matters more than the tool.
Where AI helps most
- Splitting a long function into smaller, named ones.
- Replacing nested
ifchains with early returns or a lookup table. - Renaming for clarity across a file.
- Converting callbacks to
async/await. - Writing the first draft of tests for code that has none.
These are changes with a clear before and after, which makes them easy to verify.
A workflow that keeps you in control
- Pin the behaviour with tests first. If the code has no tests, ask the assistant to write characterization tests that capture what the code does today, and run them.
- Give a narrow, specific instruction. "Extract the discount rules into separate functions. Do not change behaviour or the public signature" beats "clean this up".
- Work in small steps. One function or one concern per request. Small diffs are reviewable. Large ones get approved without being read.
- Read the diff like a pull request from a new colleague. Check edge cases, error handling and anything that was removed.
- Run the tests and commit. Then take the next step.
An example
Take a function that calculates a customer discount with a dozen conditions for membership level, coupon and season. A good prompt looks like this:
Refactor calculateDiscount for readability.
- Extract each rule into its own small function.
- Keep the function signature and the results identical.
- Do not add dependencies.
Afterwards, list any behaviour you were unsure about.
The last line is the important one. It invites the assistant to point at the places where the original code was ambiguous, and those are the places to review by hand.
What to watch for
- Silent behaviour changes. A reordered condition can change the result for one edge case.
- Invented APIs. Check that every function and option it uses actually exists in your version of the library.
- Lost handling. Error branches and logging sometimes disappear during a "simplification".
- Sensitive code. Follow your company's policy on what can be sent to an external service.
The result
Used this way, an assistant turns refactoring from a task people postpone into one they do as they go. The code gets cleaner in small, verified steps, and the tests you wrote to guard the change stay behind as a bonus.
Better instructions give better output. Our notes on prompt engineering for developers cover that side.