You open a file, scroll, and the function keeps going. Eight hundred lines. It touches the database, sends an email, mutates a global, and nobody on the team will admit to writing it. So you paste it into an LLM and ask "refactor this into modules." Twenty minutes later you have beautiful, well-named, PEP-8-compliant code that breaks payroll reconciliation in production on Thursday.
That failure is not the model's fault. It is an ordering problem. A refactoring prompt given to an LLM before you have a dependency map and characterization tests is not refactoring — it is rewriting with extra confidence. This kit is about the order: tests first, map second, code last. Each prompt below is copy-paste ready, with the failure it prevents and an example of how it reads in practice.
The trap: LLMs are trained to produce plausible code, not preserved behaviour
When you ask a model to "improve" a function, it optimises for what good code looks like, not for what your code does. So it quietly drops the try/except that swallowed an exception on a legacy third-party call, or replaces a manual loop with a library call whose edge-case behaviour differs on empty input. More on the topic: “Your Monolith Looks Fine From the Outside: A Prompt Kit That Makes an LLM Draw the Microservice Map — and Point at the Seams Where It Tears”.
There is a second, cheaper trap: the model does not see what it was not given. An 800-line function usually calls helpers defined elsewhere, reads module-level state, and depends on the order in which other code ran before it. Paste only the function and the model will confidently invent the rest.
Prompt 1: The dependency and side-effect map (run this before anything else)
This is the prompt that actually earns its keep. It asks for a structured inventory of everything the function touches — inputs, outputs, mutations, external calls, and hidden couplings — without touching the code itself.
Prompt:
You are auditing a legacy Python function before any refactoring. Do NOT propose new code.
Read the function and the surrounding module I provide. Produce a table with these columns:
| What | Kind (param / global / attribute / module-level state / external call / file or DB / time or randomness) | Read, Write, or Both | Where used (line numbers) | Risk if changed |
Then answer explicitly:
1. Which side effects are invisible from the function signature?
2. Which values does the function mutate that the caller may still be holding a reference to?
3. Which branches look dead, and what evidence do you have? If you cannot prove a branch is dead, say "unproven".
4. Which behaviour depends on call order or on state left behind by other code?
Finish with a list of questions you need answered before refactoring. Do not guess answers.
More on the topic: “LeakCanary Says Where, LLM Says Why: Prompting Your Way Out of OutOfMemoryError in Android”.
Example of how it reads back: "Mutates self.cache (dict) in place at lines 214 and 388; the caller passes a module-level dict, so the mutation outlives the call." That single line is worth more than an hour of scrolling. The "unproven" instruction matters — without it the model will label a branch dead because it looks dead, and you will delete a fallback that fires once a month.
Prompt 2: Characterization tests that pin current behaviour, bugs included
The point of characterization tests is not to check that the code is correct. It is to check that it still does what it did yesterday — including the weird parts. This is the step most people skip, and it is the only thing that lets you refactor at 5 p.m. without fear.
Prompt:
Write pytest characterization tests for the function below. Goal: lock in CURRENT behaviour, not correct behaviour.
Rules:
- Cover every branch you can reach with the inputs available. Where a branch depends on state I have not given you, write the test but mark it `@pytest.mark.skip(reason="needs <state>")`.
- For each test, add a one-line comment stating which behaviour it pins.
- Where the current behaviour looks like a bug (wrong exception type, off-by-one, silent None), still write the test that preserves it, and add a comment `# possible bug:...`.
- Use only pytest and unittest.mock. No new dependencies.
- Do not modify the function under test. Do not suggest fixes.
A typical result: eleven tests, three of them flagged as possible bugs — and one of those three turns out to be the reason a downstream nightly job never crashes. You keep the bug. You document it. You fix it in a separate, visible change with its own review.
Prompt 3: The seam-finding pass — where to cut an 800-line function
Now that behaviour is pinned, ask where the cuts go. The wrong question is "split this into functions." The right question is "which contiguous blocks share inputs and outputs and can be extracted without changing the order of side effects."
Prompt:
Given the function and the dependency map, propose a decomposition into named steps.
For each proposed step, give:
- Name and one-sentence responsibility
- Line range it covers
- Inputs it needs and outputs it returns
- Side effects it performs, in order
- Whether extracting it changes the order of any side effect relative to the others. If yes, explain and mark the step as UNSAFE to extract as-is.
Order the steps so that extraction can happen one at a time, each leaving the tests green. Flag any step that cannot be extracted without changing behaviour.
More on the topic: “Green Tests, Broken Contracts: 12 LLM Prompts That Hunt Reentrancy, Oracle Holes, and Gas Leaks Before Your Solidity Audit”.
This is where the model surfaces the real problem in most legacy functions: two side effects — say, a log write and a cache update — are interleaved, and any clean split reorders them. The "UNSAFE" flag is the deliverable, not the pretty step list. More on the topic: “CI/CD as an Art: A Real Pipeline Breakdown and Costly Mistakes”.
Prompt 4: One step at a time, with the diff under a microscope
Refactor one step per conversation turn. This is slow by design and it is the only way the tests stay meaningful.
Prompt:
Extract ONLY step "<name>" (lines X–Y) into a module-level function. Constraints:
- Do not touch any other line of the original function except the call site.
- Preserve the exact order of side effects.
- Preserve exception types and messages.
- Keep the original parameter names where they are visible to callers.
- Output a unified diff, then a list of every behavioural assumption you made that the tests would not catch.
That last line is the honest part. It forces the model to say "I assumed items is never a generator" instead of hiding the assumption inside working-looking code.
Prompt 5: The adversarial review — ask the model to break its own work
Before you merge, make the model attack the change. Models are noticeably better at finding flaws in a diff when asked to, than at avoiding them when writing.
Prompt:
Here is the original function and the refactored version. Act as a hostile reviewer.
List every input or state for which the two versions could behave differently: exception paths, empty and single-element inputs, None, mutable default arguments, time-dependent logic, floating-point ordering, and side-effect order.
For each, state whether a test exists that would catch the difference. If no test covers it, say so explicitly.
Prompt 6: The dead-branch and duplication sweep (the honest version)
LLMs are genuinely good at spotting duplicated logic and branches that can never fire — this is one of the few places where they save real hours on a big file. The catch is that they are also happy to declare things dead without proof. More on the topic: “The LLM Detective: DevTools Prompts That Reproduce Bugs, Read Stack Traces and Set Breakpoints Instead of Guessing”.
Prompt:
Scan the module for: (a) branches whose condition cannot be true given the types and constraints you can see, (b) blocks duplicated elsewhere in the module, (c) loops or calls whose result is never used.
For each finding, cite line numbers and the evidence. If evidence is incomplete, label it "suspected" and state what would confirm it. Do not recommend deletion for anything labelled suspected.
Treat "suspected" as a to-do for a human, not a licence to delete. The model does not know that a config flag flips that branch twice a year.
Where the model quietly lies, and how to catch it
Three failure modes show up again and again on legacy Python:
| What the model says | What actually happened | How to catch it |
|---|---|---|
| "This branch is dead" | It is reachable via a config flag or a rare input | Require evidence; keep the characterization test |
"Replaced the loop with sum()" |
Behaviour changes on empty input or on None values |
Adversarial review, plus a test for empty input |
| "Extracted the helper, behaviour unchanged" | Side-effect order changed | Ask for the ordered side-effect list before and after |
None of these are exotic. They are the normal output of asking a model to make code prettier without pinning what it does. The prompts above exist mainly to make those answers visible before the code lands.
The same discipline applies when you move from one big function to a whole module: the map comes before the rewrite. A related walkthrough of that decision — when to extract functions versus rewrite a module outright, and what it costs — is in “Surgery or Amputation: How to Use LLM Prompts for Legacy-Code Refactoring Without Breaking Production” (/en/blog/razobrat-monolit-ne-slomav-prodakshn-kak-ya-vybirayu-mezhdu-vyshchipyvaniem-funktsiy-cherez-llm-i-polnym-perepisyvaniem-modulya). More on the topic: “LLM Chat vs Coding Agent in 2026: How to Choose Your AI Coding Assistant by How Much of the Task You Can Specify Up Front”.
And when the refactor is done, the review pass that catches what you missed is a separate skill: prompts that hunt bugs in a diff rather than generate it. More on that: “Your Second Reviewer Never Sleeps: 12 Prompts That Catch Bugs Before the Merge Button Lights Up” (/en/blog/promty-dlya-kod-revyu-kak-zastavit-llm-nakhodit-bagi-do-merzha). More on the topic: “CI/CD Without Surprises: 12 Prompts That Make the LLM Write Pipelines, Fix Broken Builds and Explain Terraform Plans in Plain English”.
The order is the whole trick
If you take one thing from this, take the sequence. Tests that pin current behaviour. A map of every side effect and hidden coupling. A decomposition that flags unsafe cuts. Then, and only then, code — one step at a time, each step green before the next.
An 800-line function is not scary because it is long. It is scary because nobody wrote down what it does. The prompts above are mostly a way of forcing that document into existence, with the model doing the tedious part. Start with Prompt 1 on the worst function in your codebase tonight, and do not let anyone paste a refactor into the chat until the map and the tests exist.
Rules and figures are stated as of November 2026.