iTranslated by AI
[Refactoring] Practical Steps to Safely Improve 'Scary' Legacy Code with AI
Introduction
"This function is too long, I have no idea what it's doing... but I'm afraid if I touch it, it will break."
Almost every project that has been in operation for many years has "legacy code that is scary to touch." The specifications are outdated, there are no tests, and the original author has already left the company—have you given up on refactoring when faced with code like this?
In the AI era, the barrier to refactoring has dropped dramatically. This is because AI is far more persistent and faster than humans at "deciphering code" and "generating tests."
In this article, I will introduce practical steps to safely refactor black-box functionality by leveraging AI agents.
Why is AI suitable for refactoring?
The biggest hurdles in refactoring are "fully understanding current behavior" and "guaranteeing that behavior remains unchanged before and after the modification."
AI becomes a powerful partner in the following areas:
- Context Comprehension: Instantly analyzes complex, intertwined conditional branches and explains them in natural language.
- Test Generation: Can mechanically generate a large volume of comprehensive test cases.
- Pattern Application: Can execute mechanical transformations like method extraction or variable renaming without errors.
3 Steps to Safe Refactoring
Simply asking, "Make this code clean," is dangerous. Proceed through the following three stages.
Step 1: "Decoding" and "Understanding the Current State"
First, without changing the code, have the AI explain the meaning of the code.
For example, suppose you have a typical "spaghetti code" like the one below.
Target Legacy Code (legacy-order.ts):
function processOrder(o: any) {
if (o.type == 1) {
if (o.val > 1000) {
o.disc = 0.1;
} else {
o.disc = 0;
}
} else if (o.type == 2) {
o.disc = 0.2;
if (o.member) o.disc += 0.05;
}
return o.val * (1 - o.disc);
}
When you pass this code to an AI and have it explain, logic such as "type 1 is a regular order, 2 is a member order..." will be organized into natural language.
Step 2: Creating "Pinning Tests" (Characterization Tests)
Before refactoring, create tests that "pin down" the current behavior (including bugs).
Prompt Example:
Create a unit test (Jest) that guarantees the current behavior of the `processOrder` function in @legacy-order.ts.
Ensure that the condition branches are covered to achieve 100% coverage.
Test code generated by AI:
describe('processOrder', () => {
test('Type 1, >1000 should have 10% discount', () => {
expect(processOrder({ type: 1, val: 2000, disc: 0 })).toBe(1800);
});
test('Type 1, <=1000 should have no discount', () => {
expect(processOrder({ type: 1, val: 500, disc: 0 })).toBe(500);
});
test('Type 2 with member should have 25% discount', () => {
// ...
});
});
Run the generated tests and confirm that all of them pass. This will serve as your "lifeline."
Step 3: Executing Refactoring with AI
Once the lifeline is in place, ask the AI to apply techniques such as "guard clauses" or removing "magic numbers."
Prompt:
While maintaining the tests, refactor the code to turn magic numbers into constants and use early returns to reduce nesting depth.
Refactoring results by AI:
const ORDER_TYPE = { NORMAL: 1, SPECIAL: 2 };
function processOrder(order: Order): number {
let discountRate = 0;
if (order.type === ORDER_TYPE.NORMAL) {
if (order.value > 1000) {
discountRate = 0.1;
}
} else if (order.type === ORDER_TYPE.SPECIAL) {
discountRate = 0.2;
if (order.isMember) {
discountRate += 0.05;
}
}
return order.value * (1 - discountRate);
}
After every change, run the tests created in Step 2 to ensure nothing has broken.
Actual Success Story: Dismantling a "God Class"
At our company, we dismantled a massive "UserManager class" that exceeded 3,000 lines of code.
- Had the AI draw a dependency graph for each method to identify groups of methods with low coupling.
- Generated test code for each identified method group.
- Moved them to separate classes (
UserAuthService,UserProfileService) while ensuring all tests passed.
Dependency analysis, which would take days if done manually by a human, was visualized by the AI in just a few minutes.
Summary
If you leave "scary code" as it is, technical debt will continue to accumulate interest.
Now that we have AI as a powerful ally, refactoring has shifted from "fear" to "strategic improvement activity."
- Understand: Have the AI explain it.
- Pin down: Have the AI write tests that act as a lifeline.
- Improve: Make small changes and ensure tests pass.
Follow this cycle to keep your codebase healthy.
In the next article, we will discuss AI utilization strategies to improve the quality of the "test code" itself, which is the cornerstone of this cycle.
Next Step:
Part 3: [Test Automation] Don't have time to write test code? A strategy to have AI write "meaningful tests"
Discussion