When LLMs Take Over Legacy Code: A Practical Path from Refactoring to Productivity
This article explains why legacy code cannot be fixed through brute-force rewrites and how general-purpose large language models can support safer refactoring. It covers a three-stage approach: using structured prompts to help models understand existing code, scoring risk across change frequency, impact scope, and repair cost, and turning the analysis into a four-quadrant action plan. It also outlines how to build test baselines, make small incremental changes, add observability before refactoring, and write model-generated findings back into documentation. The goal is to reduce the cost of understanding and evaluating legacy systems while keeping validation and decision-making with the team.
1. Why Legacy Code Should Not Be Changed by Force
In systems that have run for many years, code aging usually does not come mainly from outdated technology choices. It comes from three more practical causes:
- Loss of meaning. The original designer’s business assumptions, boundary conditions, and temporary compromises were never fully documented. The code keeps the result but loses the reason behind it.
- Accumulated changes. Over the years, different teams have added patches under different standards. One piece of logic may have three or four equivalent implementations, and readers cannot tell which one is the correct version.
- Lack of validation. These systems often have few unit tests and integration tests. Any change must rely on production behavior as a fallback, so teams develop a collective mindset of “do not touch it unless absolutely necessary.”
Therefore, asking a general-purpose LLM to directly output an “optimized implementation” often just replaces unreadable code with another form of unreadable code. A more reasonable role for the model is as an assistant engine for semantic analysis and risk prediction, while decision-making remains with people.
2. Step One: Let the Model Understand Before It Rewrites
A prerequisite for refactoring is verifiable understanding. A practical way to start is chunked input plus structured output: ask the model to produce a “structural description” rather than new code.
1. Build a module profile
For each file or directory to be processed, require the model to answer a fixed set of questions:
- What are the externally exposed entry points (functions, APIs, message consumers, scheduled jobs)?
- What external resources does it depend on (configuration items, database tables, caches, third-party calls)?
- What implicit global states exist (singletons, static variables, shared connection pools)?
- Which branches are almost impossible to reach (dead code or legacy compatibility branches)?
The value of a fixed question set is that outputs can be compared horizontally. The team can use the same template module by module instead of improvising each time.
2. Use a three-stage summary to control context
A single file often fits into the context window, but a medium-sized legacy service can easily contain tens of thousands of lines. A practical strategy is:
Stage 1: File-level summary (within 150 characters per file, including entry points and side effects)Stage 2: Directory-level aggregation (cluster by call relationships and output a module dependency graph)Stage 3: Global hotspot identification (mark the top 10% of modules by reference frequency)
This avoids losing details while also preventing the model from contradicting itself in an extremely long context.
3. Make the model output a list of questions instead of conclusions
In practice, the most valuable output is not “this code is poorly written,” but “this cannot be determined here.” For example:
- A function reads and writes the same cache key, but the cache expiration time depends on external configuration, so it is unclear whether concurrent overwrite risk exists.
- A branch receives input from a message body and lacks format validation, but there is no way to confirm whether the upstream guarantees schema consistency.
A list of questions naturally forms an index for further investigation and follow-up, and it also prevents the model from making up facts.
3. Step Two: Assess Risk and Output Tiered Recommendations
After understanding, the next step is to translate “code problems” into “engineering decisions.” It is better to use three-dimensional scoring rather than a single “code quality” score.
1. Three dimensions
| Dimension | Basis for judgment | Typical signals |
|---|---|---|
| Change frequency | Number of commits in the past six months and related defect counts | Frequent changes plus frequent regressions |
| Impact scope | Number of callers and whether it is on the main path | Core transaction or billing paths |
| Repair cost | Missing test coverage, coupling level, external dependencies | No tests plus strong coupling |
2. Four-quadrant handling strategy
- High frequency + high impact: Add tests first, then perform small-step refactoring. Do not rewrite everything at once.
- High frequency + low impact: Optimize at low cost. This is suitable as a pilot to build team confidence.
- Low frequency + high impact: Add defensive checks and alerts only. Do not change the structure.
- Low frequency + low impact: Mark it explicitly as “frozen,” document it, and stop investing in it.
The core constraint of this matrix is: high-impact modules without test protection are not allowed to be refactored. The model can provide suggestions, but it cannot replace validation.
3. Make the model generate a validation plan
Before refactoring, require the model to produce a checklist for “how to prove the change has no side effects”: which input and output pairs need to be captured, which boundary cases need to be constructed, and where instrumentation should be added. Refactoring without this step essentially moves risk from the code to production.
4. Implementation: Turn the Process into Team Standards
- Establish a baseline: Add input and output snapshot tests for target modules to form a regression safety net.
- Commit in small steps: Limit each change to an explainable scope and state in the commit message “why it was changed.”
- Observability first: Before refactoring, integrate logging services, monitoring, and alerts so behavior changes can be measured rather than deployed based on a feeling that “everything looks fine.”
- Write knowledge back: Organize the model’s question list into documentation and comments to fill the gaps caused by lost meaning.
5. Common Mistakes
- Treating generation as authority. Model output must be treated as an unverified hypothesis, especially for sensitive logic involving money, permissions, and concurrency.
- Pursuing a one-time rewrite. The value of legacy systems lies in their operational history. Rewriting loses a large amount of implicit compatibility logic.
- Ignoring data and configuration. Many legacy behaviors are actually determined by configuration items and historical data. Changing code does not solve the root cause.
6. Conclusion
The real value of general-purpose LLMs for legacy systems is to reduce the time cost of the “understand” and “evaluate” stages, allowing teams to focus their energy on validation and decision-making. The implementation path can be summarized as: first build structured understanding, then perform tiered risk assessment, and finally use small-step refactoring and observability to contain changes. This methodology does not depend on any specific vendor product. Any mainstream intelligent coding tool and general cloud-based logging, monitoring, container, and storage services can support the same process. Baidu AI Cloud can also provide integrated support for such engineering practices, from development to operations.
