How to Refactor Legacy Code with AI

The signup script at Pinewood Trail Races was written in 2011, has grown to 1,480 lines in a single file, and still takes every race entry through mysql_query calls, a 14-branch if-else chain, and a PayPal IPN callback that nobody dares to touch. It runs, it has always run, and every developer who opens it closes it again.

This workflow refactors that kind of file with AI without stopping the race. Six phases: freeze the current behavior, map what the script actually does, extract the validation rules, replace the deprecated database layer, wrap the entry flow in tests, then rewrite in small reversible slices. Marco, the developer who maintains it, runs the whole sequence across one weekend between two race weekends. The example is a 2011 PHP registration form, but the shape applies to any file old enough that you would rather not rewrite it from scratch.

Where This Refactor Should End Up

Decide the finish line before you start cutting. A legacy refactor is not a rewrite, and mistaking one for the other is how projects stall for months.

For this script the target is specific: the same entry flow, the same database rows, the same confirmation email, but split into four files with names that describe their job, validation rules declared in one place instead of scattered across branches, parameterized queries instead of concatenated SQL, and a test that signs up a fake entrant and asserts the row landed. Nothing about the user-facing form changes. If the refactor alters what a runner sees, it has gone too far.

Keep that constraint visible in every prompt. Models love a clean-slate rewrite, and a clean-slate rewrite of a payment-adjacent script is exactly what you must not ship in one weekend. For background on how much structure a prompt needs, see our code review prompts for ChatGPT.

Phase 1 — Freeze the Behavior Before You Touch Anything

You cannot preserve behavior you have not written down. Capture what the script does today, including the odd parts.

You are a senior PHP developer helping me refactor a legacy registration script.
Below is the current script. Describe its observable behavior in a behavior contract with these sections:
- entry points (files, routes, form actions)
- inputs (every field read from POST, GET, REQUEST, or cookies)
- side effects (database writes, emails sent, files touched, redirects issued)
- outputs (what the user sees on success and on each failure path)
- external calls (payment callbacks, third-party endpoints)
Describe what the script does, not what it should do. Where behavior looks like a bug, note it as OBSERVED BEHAVIOR with a warning flag and keep it in the list.

You get a behavior contract you can compare against at the end. The instruction to keep observed bugs in the list matters: half of legacy “bugs” are load-bearing, and a refactor that silently fixes them breaks the business process that grew around them.

Phase 2 — Map Responsibilities and Data Flow

A 1,480-line file usually mixes five jobs that should never share a scope. Name the jobs before moving anything.

Analyze the script below and produce a responsibility map.
For each responsibility give: a short name, the line ranges it occupies, the data it reads, the data it writes, and the other responsibilities it depends on.
Then trace the data flow in plain text from the HTTP request to the final response, listing every transformation the entrant data passes through.
Flag any responsibility that both reads and writes the same table, and any block of logic that appears in more than one place.

You get four or five named responsibilities, typically form rendering, field validation, database persistence, payment callback handling, and confirmation email, plus a text data-flow line. Duplicated validation blocks jump out here, and each duplicate is a place where the rules already disagree with each other.

Phase 3 — Extract the Validation Rules into One Place

Validation is the safest thing to move first: it is pure, it is testable, and it is where the real bugs live.

The script validates entrant data across a chain of nested conditions.
Rewrite that validation as a single declarative rules list, one rule per field.
For each rule give: field name, rule type (required, format, range, cross-field), the exact condition in plain English, and the error message currently shown to the user.
Preserve the current behavior exactly, including the order in which errors are reported.
Then list every rule that contradicts another rule, or that can never be reached because of the order of the conditions.

You get a rules list plus a contradiction report. In a 14-branch chain written over a decade, at least two branches are dead code and at least one pair of rules disagrees about whether an emergency contact is required. Both findings are worth the whole exercise.

Phase 4 — Replace the Deprecated Database Layer

Now the risky part. Do it after the mechanical work, and keep the slice narrow.

List every database interaction in the script and convert each one to an equivalent prepared statement.
For each call give: the original function call, the SQL string, the parameters and their source, the replacement using parameterized queries, and the return handling that must change.
Do not change the query logic, the table names, or the column order.
Flag any call where a parameter comes directly from user input and could currently reach the SQL string, and mark it as an injection risk with its current exposure.

You get a one-to-one mapping you can apply mechanically, plus an injection-risk list. The risk list is not a bonus; it is often the reason the refactor is justified in the first place. If the same input can reach both a query and an email header, note that too.

Phase 5 — Wrap the Entry Flow in Tests

Tests before the rewrite, not after. Without them you are trusting your own reading of the old file.

Write PHPUnit tests for the entry flow based on the behavior contract below, not on the current implementation.
Cover: a fully valid entry, a missing required field, an invalid email format, a duplicate entry for the same race, a declined payment callback, and a successful payment callback.
For each test state the setup, the action, and the assertion in plain English first, then give the test code.
Where behavior is ambiguous, write the test to assert the observed behavior and add a comment marking it as a decision to confirm.

You get a suite that documents the contract as executable assertions. Run it against the untouched script before you change a line. If a test fails on the original code, you just learned something about the original code, and that is the cheapest moment to learn it. Our guide to writing unit tests with ChatGPT covers the assertion detail.

Phase 6 — Rewrite in Reversible Slices

Never ask for the whole file back. Ask for one responsibility, wired behind the old entry point, with a switch back to the old path.

Rewrite only the validation responsibility identified in phase 2.
Constraints:
1. Keep the original entry point and its signature unchanged.
2. Return the same error structure the old code returned.
3. Add a config flag so the old validation can be restored without a code revert.
4. Do not touch database code, payment handling, or the email template in this pass.
Output the new file, the one-line change needed at the call site, and the tests from phase 5 that should now pass.

You get one file, one call-site change, and a green test run. Repeat per responsibility. Six small passes with a working system after each one beats a single 1,480-line rewrite you cannot debug at 11 p.m. the night before a race. When a pass fails, restore the flag and you are back to a working site in one deploy.

What the Finished Refactor Looks Like

  • A behavior contract that matches the old script’s observed outputs.
  • Five named responsibilities with line ranges and data dependencies.
  • One declarative validation rules list, plus a contradiction and dead-code report.
  • Parameterized queries with a one-to-one mapping from the old calls.
  • A test suite covering six entry-flow paths, green before and after each slice.
  • Four files with descriptive names, each behind a switchable entry point.

Traps That Break Legacy Refactors

Trap 1 — asking for the whole file at once. A model asked to rewrite 1,480 lines will silently drop branches it cannot fit. Slice by responsibility.

Trap 2 — fixing “obvious” bugs mid-refactor. A refactor that changes behavior is a rewrite wearing a disguise. Record the bug, ship the refactor, fix the bug next.

Trap 3 — trusting the AI’s read of the code. Reread the responsibility map against the file yourself. Models summarize confidently and miss the one branch that only runs on leap days.

Trap 4 — no rollback path. If the only way back is reverting a commit, you will deploy less often and find problems later. Keep the flag.

To debug what a slice broke, the loop in our debug code with ChatGPT workflow pairs well with phase 6.

Sources & Notes

The freeze, map, extract, replace, test, and slice sequence is our own framing of standard legacy-refactor practice, reviewed on 2026-10-09. Pinewood Trail Races, Marco, and the 1,480-line signup script are illustrative; the line counts, deprecation states, and payment-callback details are examples rather than a description of any real file. Refactoring a payment path carries financial and legal exposure, so run your own security review before shipping. Model output changes between versions, so re-run the behavior check whenever you switch models.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM