Legacy Refactor
The biggest legacy risk is not ugliness but not knowing what will break. Establish a behavior baseline, find seams and replace in small steps; use AI to read code and generate tests, not to rewrite everything at once.
Workflow
- 1
Map calls and baseline behavior
Use IDE call hierarchy and logs to map entry points, dependencies and side effects. Add end-to-end tests or record real requests for critical paths to lock current behavior, including seemingly odd logic.
- 2
Find seams instead of rewriting
Start at dependency boundaries, pure functions and interfaces; wrap external calls in adapters. Move one responsibility at a time and keep changes revertible; never refactor and change requirements in the same commit.
- 3
Characterization tests and diffing
Have AI generate characterization tests from the current code, focusing on boundary inputs and error paths. Compare new output against the old implementation as an oracle and explain every difference.
- 4
Canary replacement and rollback
Run old and new implementations in parallel, shift traffic gradually and monitor error rate, latency and business metrics. Keep a one-switch rollback and delete the old code only after stability.
Recommended prompts
Code Refactor Prompt
Get a step-by-step refactor plan with behavior-preserving verification.
Unit Test Generation Prompt
Generate runnable tests with edge cases, not just the happy path.
Bug Diagnosis Prompt
Turn an error, logs and code into a verifiable debugging path.
FAQ
How do I start with untested legacy code?
Record real requests at the most stable, critical entry points as regression samples, then add characterization tests. Do not chase coverage first.
Can AI rewrite an entire module?
It can generate a candidate, but never ship it directly. Have it explain implicit rules first, then replace in steps and verify old versus new.
Related skills
AI Code Review
Use AI for a first review pass so human attention goes to architecture, edge cases and security instead of formatting.
Test Generation
Generate tests that catch real defects instead of happy-path ceremony.
Long-Form Blog Production
A repeatable pipeline from topic selection and research to a 3,000-word draft and fact-check.