Legacy code is where teams lose the most time — but it is also where AI saves the most time, if you prompt carefully. The key rule for refactoring with AI is simple: behaviour must stay identical, only structure should change.
Refactoring is the art of improving the shape of code without changing what it does. AI tools are dangerously good at producing "improved" code that subtly changes behaviour — renaming variables, dropping seemingly redundant checks, or replacing a custom utility with a library function that has slightly different semantics. This tutorial teaches you how to prompt for behaviour-preserving refactors, and how to verify the AI actually preserved that behaviour.
A refactor is a controlled transformation: you start with code that works, change its structure, and end with code that still works exactly the same way. The four common refactor goals are readability, testability, performance, and safety (e.g. extracting magic numbers, adding type narrowing). A prompt should pick one of these as the primary goal so the AI knows what to optimise for.
Imagine renovating a house: you do not knock down a load-bearing wall on a hunch. You plan, prop it up, take one wall down, check the structure, then move on. AI refactoring works the same way — small, verifiable steps beat a single mega-rewrite every time.
The instinctive prompt is "clean this up". The AI interprets that as licence to rewrite everything, often inventing new function signatures, changing return types, or silently fixing what it considers a bug.
Weak prompt
refactor this and make it cleaner
function processOrders(orders) {
let total = 0;
for (var i = 0; i < orders.length; i++) {
if (orders[i].status == "paid") {
total = total + orders[i].amount;
}
}
return total;
}
You will get something terser — but also probably with stricter equality, an early return, a different name, and a switch from var to const. Any of those could clash with the rest of your codebase, and the AI changed several things at once so you cannot tell which change was harmless.
Strong prompt
Language: JavaScript (Node.js 20, ESM, no TypeScript)
Goal of refactor: readability only — do NOT change behaviour, name, or signature.
Current function:
```js
function processOrders(orders) {
let total = 0;
for (var i = 0; i < orders.length; i++) {
if (orders[i].status == "paid") {
total = total + orders[i].amount;
}
}
return total;
}
```
Refactor constraints:
- Keep the function name `processOrders` and its parameter name `orders`
- Keep the return value identical for every input (including empty arrays)
- Use `===` instead of `==` only if it changes no behaviour for the data shape:
`[{ status: string, amount: number }]`
- Prefer Array methods over imperative loops
- No new dependencies
- No try/catch unless I ask
- Output: the new function, plus a short bullet list of every change you made
and why each one is safe
This locks the signature, names the language version, picks one goal (readability), pre-approves a specific equality change, and demands a change-log. The output becomes auditable — you can verify each change individually.
Tip: For larger refactors, ask the AI to propose the steps first ("List 4–6 small refactors I can apply one at a time, each behaviour-preserving"). Then execute them one prompt at a time. Big-bang rewrites are where bugs hide.
Find a function in your codebase older than a year. Write the strongest refactor prompt you can for it, with the goal "readability only, no behaviour change". Run the result. Diff it carefully. How many things did the AI change that you didn't approve?
Take a long function (50+ lines). Ask the AI to "propose 4 small refactors that would each improve testability, in order from safest to riskiest." Apply only the first one. Repeat next week. This is how senior engineers refactor — small steps, big wins over time.
Pick a function with no tests. First, ask the AI to write characterisation tests that pin down the current behaviour (including any weirdness). Then ask it to refactor for clarity. Run the tests on the refactored version — did anything go red?
Sign in to join the discussion and post comments.
Sign inFoundations of Prompt Engineering
The must-know basics of prompt engineering. Learn what prompts are, how AI models read them, and how to write clear instructions that get great results.
Prompt Engineering for Data Science & Analytics
Supercharge your data workflows with AI. 15 practical tutorials on using prompt engineering for data cleaning, EDA, machine learning, SQL, visualisation, and more.
Prompt Engineering for Education & Learning
Use AI as your personal tutor. Learn how to study faster, create lesson plans, generate practice questions, master languages, and prepare for competitive exams with smart prompts.
Prompt Engineering for Specific AI Tools
Tool-by-tool mastery — deep dives into ChatGPT, Claude, Gemini, GitHub Copilot, Midjourney, Stable Diffusion, and more. Learn the exact prompting techniques each platform rewards.
Prompt Engineering for Content & Copywriting
Write blogs, ads, emails, and social media content ten times faster with AI. 13 practical tutorials on prompt engineering for content creators and copywriters.
Prompt Engineering for Business & Productivity
Use AI to work smarter — automate tasks, make better decisions, and communicate professionally. 12 practical business prompt tutorials for professionals.