Last October a colleague inherited an order module that had been in production for three years. The core function started at line 412 and ended at 1213. Eight hundred lines.
He spent two evenings pulling out six smaller functions by feel, compiled clean, clicked through the checkout flow twice, and merged.
On day three, coupon amounts came out doubled for some orders. The function he had extracted quietly mutated a temporary variable from an outer loop; move the order of statements, and the meaning changes. He went back to add tests as a safety net and discovered the function's input depended on seven pieces of global state. He could not write a single test case.
Three commits reverted, one week of backfilling characterization tests, then he tried again.
Wrong order isn't just wasted work. It's negative work.
Here's the conclusion up front: write tests first, but not unit tests — characterization tests. And before you split responsibilities, make the AI inventory the code without changing it.
The order is: inventory call sites → lock current behavior with characterization tests → split along the inventoried boundaries → run tests after each cut.
Where the failure actually happened
His mistake wasn't extracting functions. Those six functions weren't ugly. He got two things wrong.
He mixed "understand the code" with "change the code" into one step. Attention is finite across 800 lines. By the fourth section, the temporary variable reused in the first section is long forgotten. AI has the same failure: paste 800 lines and say "refactor this", and it will miss cross-section state coupling, because it has no runtime and cannot see a variable's real lifetime.
He had no evidence that behavior was unchanged. Clicking through checkout twice covers maybe 20% of branches; the coupon edge cases never fire. Refactoring is defined as changing internal structure without changing external behavior. If you never pinned down the original behavior, what exactly are you proving?
Most teams fail this way: tests are added last, the function turns out to be untestable, testing is abandoned, the split happens anyway, and everyone bets. Win the bet and it's skill. Lose it and it's an incident.
Why you can't just ask the AI to rewrite it
This isn't about model capability. It's about the shape of the task.
The problem with a long function is never the line count. It's that responsibilities are tangled and state is borrowed across sections. Paste the whole thing and the model returns something that looks tidier — better variable names, one less nesting level — but its cut points are based on textual similarity, not your business boundaries. Two blocks that look alike textually may belong to pricing and to risk control respectively. The model cannot tell.
Worse, you may not be able to read what it changed. 800 lines collapsed into six functions produces a wall of red and green. Verifying it line by line takes longer than reading the original.
The right usage: let the AI do the non-destructive work first — inventory. Spend its capacity on structure recognition. Once boundaries are confirmed, let it rewrite, one boundary at a time.
Same as a mechanic. You don't let them tear the engine apart on arrival. Hook up the diagnostic scanner, read the fault codes, then start.
Step 1: inventory only, change nothing
Copy the target function into a scratch file (say order_calc.bak). Don't skip this — every subsequent cut is compared against it.
Then ask the AI to inventory. The key is putting "do not change the code" at the very front. Models follow opening instructions noticeably better than closing ones.
The version that goes off the rails:
Refactor this 800-line function into clean small functions. Code below. You get a rewrite you can neither verify nor reject.
The version that works:
You are my pair-refactoring partner. Do not change any code yet. First list every call site in this function that touches the database or an external interface, with line numbers. Then label each block as one of: pure computation / IO / state mutation, and output a table. I will use that table to decide the split boundaries. Expected output is a three-column table: approximate line range, category, what the block does.
This is where a human must step in: the AI routinely labels "read from global cache" as pure computation, because it can't see that it's a remote call. Scan the table line by line and manually re-label anything touching network, files, database, or globals as IO or state mutation.
Acceptance for this step is simple: the number of blocks marked "state mutation" should equal the number of external states you remember this function mutating. If it doesn't match, something was missed — ask the AI to expand the suspicious blocks separately.
Why first: the worst split is one that puts shared-state logic into two functions, where a change in call order changes behavior. The coupon bug came from a temporary variable shared inside a range that got cut in half. Mark state mutations in red before you cut, and you won't separate them.
Step 2: pin down current behavior
Now write characterization tests.
A characterization test doesn't verify correctness. It verifies that behavior after the change is identical to behavior before. It's allowed to be ugly. It's allowed to assert weird numbers copied from production logs.
If the function is directly callable with few dependencies, write normal tests. If it depends on seven globals like his did, use golden file testing: take 10–20 real production inputs (desensitized), dump the current output as a snapshot file, and diff snapshots after each change. In Python, unittest plus assertEqual on strings. In Java, JUnit plus a snapshot library, or just read the file and compare yourself.
Scale changes the approach. A dozen inputs: hand-pick typical samples. Thousands: batch-extract from logs, but eyeball the snapshots for sensitive fields first.
AI can help by generating samples and assertion skeletons — but never trust the expected values it invents. Ask it to write assertions and it will produce a plausible-looking amount, say 99.00, when the real order was 98.90 because of a rounding rule. Let it write the structure; fill the assertion values from snapshots yourself.
Here is an order pricing function and its input shape. Write the skeleton for characterization tests. Requirements: 1) Python unittest; 2) method names in the form test_<behavior>_<scenario>; 3) at each assertion, write # TODO fill snapshot value as a placeholder — do not invent expected values; 4) three sample inputs covering a normal order, an order with a coupon, and an order with a return. One gotcha you only learn by doing it: floats and timestamps in snapshot files drift slightly between runs, so a full string comparison fails repeatedly. Either normalize before comparing (replace timestamps with placeholders) or ignore those lines. Skip this and your suite turns permanently red, and then nobody looks at it.
Step 3: one cut at a time
With tests in place you can cut. The rhythm: extract one function, run the characterization tests immediately, proceed only when green. This is the step where people rush, and rushing replays the whole story.
The rewrite prompt needs three things: the inventory table, which single block is in scope, and a prohibition on behavior change.
Based on the classification table above, extract only block 3 ("compute line-item subtotal") into its own function. Do not touch a single other line. Requirements: 1) the new function receives only the parameters it actually uses and must not access globals; 2) if it turns out to require global state, stop and tell me — do not force the extraction; 3) give me a new-vs-old comparison marking which statements were moved and which were rewritten. Behavior must be identical. Requirement 2 is the important one. It prevents the AI from dragging shared state into the new function just to finish the task. Often it really will stop and say "this block depends on outer variable x" — which tells you the boundary choice was wrong. Pick a different block.
Run the tests after each cut. If they go red, don't hand-edit — revert the entire diff for that step, get back to the order_calc.bak baseline, and choose a different boundary. That's the payoff of one-cut-at-a-time: when it breaks, you know whose fault it is.
An 800-line function typically needs five to eight cuts, ten to thirty minutes each. It looks slow. Compare it against one week of revert plus backfilled tests.
How do you know it's done
"Tests are green" is not enough — tests only cover the samples you fed them. Three layers, loosest to strictest:
| Layer | What to check | How AI helps | Failure signal |
|---|---|---|---|
| Behavior | Characterization tests all green | Ask AI to diff old vs new and list every moved statement | Any statement "conveniently rewritten" |
| Structure | Each new function has one responsibility | Give AI the list and ask it to name each function | Names containing "and" |
| Readability | A newcomer understands it | Ask AI to role-play an unfamiliar colleague guessing purpose from signatures alone | More than one wrong guess |
The structure check is surprisingly effective. If the names the AI produces contain "and" or "as well as", the function still has two responsibilities. A name is the most honest mirror of responsibility.
The readability check is harsher: ask the AI to pretend it just joined and describe what each function does from its signature and comments alone. If it guesses wrong, the responsibilities aren't clean yet. This works especially well on 800-line functions, because you've read them so often you can no longer see the problem — the AI has no such baggage.
When not to use this
The function is about to be deleted or replaced. Don't refactor it. Writing the replacement is cheaper.
It's long but linear and branch-free. A few hundred lines of config assembly, sequential, no shared state, no conditionals. Extracting it is low risk; skip the characterization tests. Don't run the full ceremony out of principle.
There is no reproducible input source. Hardware-dependent or random-number-dependent code can't be snapshotted. Characterization testing degrades to manually diffing printed logs, and AI can only tidy the logs, not verify.
The code is too rotten for the AI to read. Seven levels of nesting and variables named a1, a2, a3 will produce a garbled inventory. Rename and flatten first until readability reaches a passing grade, then talk about splitting.
My own rule is conservative: if it runs and has no tests, don't split it. Spend half a day on characterization tests rather than betting on your memory and the model's output.
Three sentences to make it a habit
You don't need a methodology. Carve three questions into your workflow:
Before touching anything, ask "where is state shared?" and make the AI inventory only. Before cutting, ask "what pins the current behavior?" — no answer, no cut. After each cut, ask "what exactly did this change?" — can't answer, revert.
Those three map exactly to the three failures: no state inventory, no behavior lock, too much changed at once. Save them as a fixed prompt and paste it at the start of every refactor; let the AI act as your checklist.
And tomorrow's first move: pick one long function you own. Don't change it. Paste it to the AI and ask for the call-site classification table using the first prompt above. Scan the table. Half an hour, and you'll know whether that function deserves to be split right now.
I wrote this order up as a longer field note with all three prompt texts, the exact acceptance questions for each layer, and the golden-file test scaffold: Long function refactoring: test first or split first? (Chinese). It also covers several real cases where the model mislabeled cache reads as pure computation — worth scanning before you cut.


