To refactor legacy code with AI without breaking production, lock down current behavior with characterization tests first, then ask the model for one small, scoped change at a time that keeps external behavior identical, and make it explain anything odd before it touches it. The prompts below follow that sequence: map the code, capture behavior, plan small steps, refactor one step, and review the diff. Each one is copy-ready and annotated so you can adapt it to your codebase.
Refactoring, in Martin Fowler’s definition on refactoring.com, means changing a program’s internal structure without changing its observable behavior, through a series of small steps that keep the system working after each one. That definition is the whole safety model. An AI assistant that “improves” behavior while restructuring code is not refactoring, and that is exactly where production incidents come from.
Why legacy code is harder for AI than new code
Legacy code is risky to refactor with AI because its most important behavior is often invisible from the file the model is reading. A model sees the text you paste. It does not see the cron job that parses this function’s log output, the report that depends on a rounding quirk, or the customer whose integration relies on an error message wording.
The usual hidden dependencies include:
- Callers outside the file, including reflection, dynamic dispatch, string-based lookups and other repositories.
- Side effects such as writes to globals, caches, files or the database that a “pure-looking” function performs.
- Quirks that became contracts: an off-by-one, a swallowed exception or a specific sort order that downstream code now expects.
- Runtime and library versions: code that relies on behavior of an old framework version. Models also tend to suggest APIs that have since been removed, a problem covered in why AI coding assistants keep suggesting deprecated APIs.
- No tests, which is close to the definition of legacy code for many teams and means nothing will catch a behavior change.
Models also have a strong pull toward “fixing” what looks wrong. Ask for a cleanup and you may get a cleanup plus a corrected null check, a changed default and a different exception type, all mixed into one diff. The prompts below are designed to separate those concerns.
The workflow at a glance
| Step | Goal | Output you should get | Gate before moving on |
|---|---|---|---|
| 1. Map | Understand what the code does and what touches it | Plain-English summary, side effects, suspicious spots | You agree with the summary |
| 2. Capture | Freeze current behavior | Characterization tests that pass on the current code | Tests are green on unchanged code |
| 3. Plan | Break the refactor into small steps | Ordered list of behavior-preserving steps | Each step is independently shippable |
| 4. Refactor | Apply one step | A small diff plus a list of out-of-scope findings | Tests still green, diff reviewed |
| 5. Review | Hunt for behavior changes | List of any observable differences | No unexplained differences |
Repeat steps 4 and 5 for each item in the plan, committing after each green step so any problem can be reverted in isolation.
Prompt 1: Map the code before changing it
The mapping prompt asks the model to describe the code and flag anything unusual, without proposing changes yet. Separating analysis from rewriting stops the model from committing to a design before it has looked closely.
You are reviewing legacy code before a refactor. Do not suggest changes yet.
Context:
- Language/runtime: Python 3.8, Django 2.2 (do not assume newer versions)
- This module has no tests. It runs in production and handles invoice totals.
- Known callers: billing/views.py, reports/monthly.py, a nightly cron job (code not shown)
<code>
[paste the function or class]
</code>
1. Summarize in plain English what this code does, step by step.
2. List every input it reads (arguments, globals, settings, env vars, DB, files, time).
3. List every side effect (writes, mutations, network, logging, exceptions raised).
4. List anything unusual or non-obvious. For each, say whether it looks intentional
or accidental, and why. Do not assume accidental code is safe to remove.
5. List what you cannot determine from this code alone and would need to see.
Why the parts matter: pinning the runtime version prevents modern-syntax suggestions that will not run on your servers. Listing known callers tells the model the function has a contract. Question 4 is where buried business rules show up, and question 5 gives the model a legitimate way to say “I don’t know” instead of guessing. Read item 4 carefully and ask the people who know the system about anything marked intentional-but-unexplained.
Prompt 2: Capture current behavior with characterization tests
A characterization test records what the code does today, not what it should do. The term comes from Michael Feathers’ book Working Effectively with Legacy Code; the idea, as summarized in the Wikipedia entry on characterization tests, is to treat observed behavior as required behavior and let the tests act as change detectors. The same technique is sometimes called golden master testing when it compares whole outputs.
Write characterization tests for the code below using pytest.
Goal: capture CURRENT behavior exactly, including behavior that looks like a bug.
Do not fix anything. If a case looks buggy, still assert the current result and
add a comment: # CURRENT BEHAVIOR - possibly a bug: <reason>
Cover:
- Typical inputs (3-5 cases)
- Boundaries: empty, zero, negative, None, very large, rounding edges
- Every branch and every exception path you identified in the map
- Side effects: assert on what is written or mutated, using mocks only where a real
dependency cannot run in tests
Freeze time and any randomness. Do not change the code under test.
<code>
[paste]
</code>
Run these tests on the unchanged code before anything else. If a test fails on the original code, the test is wrong, not the code; fix the test until the whole suite is green. Then check coverage on the target function and ask for more cases on any branch that is not exercised. For broader test-writing prompts, see our guide to AI prompts for writing unit tests.
The “possibly a bug” comments become your list of real fixes, which you will handle later as separate, deliberate behavior changes with their own review.
Prompt 3: Plan the refactor as small steps
A refactoring plan breaks one large cleanup into a sequence of small transformations, each of which keeps the tests green. Small steps make AI-generated diffs reviewable and make failures easy to locate.
Goal: make calculate_invoice_total() readable and testable in isolation.
Constraints:
- External behavior must stay identical: same signature, return values,
exceptions, side effects, and log messages.
- Stay compatible with Python 3.8 and Django 2.2.
- Each step must leave the code working and the characterization tests passing.
Propose an ordered list of refactoring steps (for example: extract function,
rename variable, replace magic number with named constant, separate I/O from logic).
For each step give: the name of the refactoring, what changes, the risk (low/med/high),
and how a reviewer can confirm behavior did not change.
Do not write the code yet.
Reorder the plan if needed so that the safest, most mechanical steps (renames, extracting pure calculations) come first. Steps that separate input/output from logic are especially valuable, because they make the remaining code easy to unit test.
Prompt 4: Refactor exactly one step
The scoped refactor prompt asks for one step from the plan and forbids changes outside it. Anything the model notices beyond the scope goes into a list instead of into the diff.
Apply ONLY step 2 from the plan: "Extract the discount calculation into a pure
function apply_discounts(lines, customer_tier)".
Rules:
- Change nothing outside this step. No renames, formatting changes, type changes,
or "while I'm here" fixes elsewhere.
- Keep the public signature of calculate_invoice_total() unchanged.
- Preserve exceptions, rounding, ordering, and log message text exactly.
- If you think anything outside this step should change, do not change it.
List it under "OUT OF SCOPE" at the end with file and line.
Return:
1. The diff (unified format).
2. One paragraph explaining why behavior is unchanged.
3. OUT OF SCOPE list.
Why a unified diff: it keeps the change small and lets you see every removed line, which is where silent behavior changes hide. Run the characterization tests, review the diff, commit, then move to the next step. A clear commit per step also makes later debugging easier; our prompts for commit messages and pull requests help document each one.
Prompt 5: Review the diff for behavior changes
A behavior review asks a fresh session to compare the old and new code and argue that they differ. Asking the model to find differences, rather than to confirm equivalence, makes it look harder.
Compare BEFORE and AFTER. Your job is to find any observable difference in behavior.
<before>...</before>
<after>...</after>
Check specifically:
- Return values for None, empty, zero, negative and boundary inputs
- Exception types, messages, and when they are raised
- Floating point vs Decimal, rounding mode, integer division
- Order of operations with side effects (writes, logging, cache updates)
- Mutation of arguments that callers might rely on
- Evaluation order and short-circuiting changes
- Default argument values (including mutable defaults)
For each difference: input that triggers it, old result, new result.
If you find none, list the three riskiest areas a human should double-check.
For a more general review checklist beyond behavior equivalence, see our AI code review prompts.
A worked example: what a scoped refactor looks like
The illustrative function below is typical legacy code: logic, configuration and side effects in one place, with a quirk that matters.
# BEFORE (illustrative)
def calculate_invoice_total(invoice):
total = 0
for l in invoice.lines:
total += l.qty * l.price
if invoice.customer.tier == "gold":
total = total * 0.9
if total > 1000:
total = total - 50
invoice.total = round(total, 2)
invoice.save()
log.info("total=%s" % invoice.total)
return invoice.total
A careless “modernize this” request might return a version that uses Decimal, applies the 50 discount before the gold discount “because it is cleaner”, switches the log to an f-string with a different format, and removes invoice.save() because “the caller should save”. Every one of those is a behavior change. Floating point to Decimal alone can change cent values, and changing discount order changes the total for any gold invoice over the threshold.
A scoped step-2 refactor keeps everything observable and only moves the pure calculation:
# AFTER step 2 (illustrative)
GOLD_MULTIPLIER = 0.9
LARGE_ORDER_THRESHOLD = 1000
LARGE_ORDER_DISCOUNT = 50
def apply_discounts(subtotal, tier):
total = subtotal
if tier == "gold":
total = total * GOLD_MULTIPLIER
if total > LARGE_ORDER_THRESHOLD:
total = total - LARGE_ORDER_DISCOUNT
return total
def calculate_invoice_total(invoice):
subtotal = 0
for l in invoice.lines:
subtotal += l.qty * l.price
total = apply_discounts(subtotal, invoice.customer.tier)
invoice.total = round(total, 2)
invoice.save()
log.info("total=%s" % invoice.total)
return invoice.total
# OUT OF SCOPE
# - Float arithmetic for money may produce cent rounding errors; consider Decimal
# as a separate, reviewed behavior change.
# - Threshold is checked after the gold discount; confirm this ordering is intended.
The out-of-scope notes are the valuable part: they surface two real business questions without silently answering them. The magic numbers became named constants, which is itself a separate small step you could split out if you prefer even smaller diffs.
Security checks during a refactor
Security-sensitive code needs extra review during refactoring, because a structural change can quietly remove a check. Moving a function can drop an authorization decorator; extracting a query builder can turn a parameterized query into string concatenation; simplifying error handling can start leaking stack traces to users.
When the code touches authentication, access control, input handling, cryptography or error handling, add this to the review prompt, using the categories of the current OWASP Top 10:2025 as the checklist:
Additionally, check whether the AFTER version weakens security compared with BEFORE,
using OWASP Top 10:2025 as a checklist. In particular:
- A01 Broken Access Control: any authorization check removed, moved later, or bypassed?
- A05 Injection: any parameterized query, escaping, or validation removed?
- A04 Cryptographic Failures: any change to hashing, randomness, or key handling?
- A10 Mishandling of Exceptional Conditions: any exception now swallowed, or any
error path that now fails open instead of closed?
Report only concrete findings with line references.
Also never paste secrets, credentials or customer data from legacy code or config into a prompt. Replace them with placeholders before sharing the code.
When the change is bigger than a function
For a module or service that needs replacing rather than tidying, AI-assisted rewrites carry the same risks at larger scale. Martin Fowler’s Strangler Fig Application article recommends gradual modernization instead of a full replacement: build new components alongside the legacy system, find seams where behavior can be split off, and move it over piece by piece while both run.
AI fits that approach well when you use it per seam: map one seam, write characterization tests at that boundary (often at the HTTP or message level), generate the new implementation, and run both against the same inputs before switching traffic. Asking a model to rewrite a whole legacy service in one go removes all the checkpoints that make the process safe.
Mistakes that turn a refactor into an incident
- Refactoring and fixing in the same change. Keep bug fixes as separate commits with their own review and tests.
- Trusting tests the AI wrote against the new code. Tests must be written and passing against the old code first, or they only confirm the new behavior.
- Not telling the model the runtime version. The result may not run in production.
- Accepting large diffs. If a diff is too long to review carefully, ask for a smaller step.
- Deleting “dead” code on the model’s word. Search the whole codebase, configs and other repositories, and check logs or metrics for calls before removing anything.
- Skipping the out-of-scope list. It is often the best documentation of the system’s hidden rules you will ever get; turn it into comments or tickets. Our prompts for code comments and inline documentation can help capture why a quirk exists.



