Legacy code. It's the code that runs the world's banks, airlines, and logistics systems. It's also the code that makes developers wake up in a cold sweat. The term 'legacy' isn't about age—it's about code that's hard to change, understand, and test. But here's the thing: rewriting from scratch is usually a disaster. As Joel Spolsky famously argued in 'Things You Should Never Do' (2000), rewriting code throws away years of embedded bug fixes and domain knowledge. The smarter move is to refactor incrementally, and AI is the perfect partner for this. In this post, I'll share 15 battle-tested prompts that help me analyze, refactor, and optimize legacy code without pulling my hair out.
1. Map the Minefield: Dependency Graph Analysis
Prompt:
Analyze the dependencies in this legacy codebase. Generate a dependency graph showing which modules depend on each other. Identify circular dependencies and modules with excessive fan-in (many dependents) or fan-out (many dependencies). Output a clear summary: top 5 'god modules' that should be split, and any cycles that need breaking. For each issue, suggest a concrete refactoring strategy (e.g., extract interface, use dependency injection, apply mediator pattern).
Example: I used this on a Java banking app with 200k lines. The AI found a 7-module circular dependency that caused nightly builds to fail randomly. We broke it by extracting a shared 'core' module, cutting build time by 40%.
Why it works: AI can quickly parse huge codebases and produce visual maps that would take a human days. The prompt forces it to prioritize actionable items.
2. The God Class Slayer: Decompose Large Classes
Prompt:
Identify the largest classes in this codebase (by lines of code). For each, list its responsibilities (SRP violation check) and suggest how to split it into smaller classes. Provide a step-by-step refactoring plan with code snippets for the new classes and the modified original. Include migration notes for callers.
Example: A C# 'OrderManager' had 5,000 lines and 20+ responsibilities. AI split it into OrderValidator, OrderCalculator, OrderRepository, and OrderNotifier. The result: unit test coverage went from 30% to 80% in a month.
Why it works: This prompt guides AI to apply Single Responsibility Principle systematically, generating ready-to-use code that fits the existing style.
3. Dead Code Exorcist: Find and Remove Unused Code
Prompt:
"Scan this codebase for dead code: unused classes, methods, variables, and unreachable branches. List every item with its location and a confidence score (high/medium/low). For high-confidence items, show the removal diff. Exclude any code that might be used via reflection, serialization, or dynamic invocation—flag those for manual review."
Example: In a Python project, AI found 15% of the codebase was dead, including a 500-line 'legacy_parser' that hadn't been called in years. Removing it reduced the attack surface and simplified onboarding.
Why it works: AI's pattern matching can spot unused declarations, but the prompt adds a safety net for dynamic usage.
4. Spaghetti Code Comber: Extract Methods
Prompt:
"Read the following method (paste code). It's too long and has nested conditionals. Refactor it into smaller, well-named methods. Preserve the exact behavior. Add comments where the intent is unclear. Show the before/after diff."
Example: A 300-line COBOL-like method in a legacy PHP app was refactored into 10 focused methods. The AI also suggested renaming variables from $a, $b to $orderId, $totalPrice. The code became readable, and the next maintenance task took half the time.
Why it works: This is the classic 'extract method' refactoring, and AI excels at it, even with messy code.
5. The Oracle Decoder: Understand Obscure Logic
Prompt:
"Explain what this code does in plain English, as if to a junior developer. Break it down into sections: purpose, inputs, outputs, side effects, and any tricky parts. Then suggest a modern alternative implementation (e.g., use a standard library or design pattern)."
Example: We had a Perl script that parsed log files with regexes. AI explained it was doing a state machine, then showed a proper state machine implementation in Python, reducing lines from 200 to 50.
Why it works: AI can reverse-engineer intent from code, which is invaluable for code without documentation.
6. Performance Autopsy: Find Bottlenecks
Prompt:
"Analyze this code for performance issues: N+1 queries, O(n^2) loops, unnecessary resource allocation, lack of caching, etc. For each issue, show a benchmark (if possible) or explain the impact. Provide a refactored version with better performance, and include a before/after complexity analysis."
Example: A legacy Java app loaded a list of customers and for each made a database call. AI identified the N+1 pattern and replaced it with a single JOIN query. Response time dropped from 8 seconds to 0.5 seconds.
Why it works: AI knows common performance anti-patterns and can generate optimized code, but be sure to actually benchmark before/after.
7. Test Enabler: Generate Unit Tests for Legacy Code
Prompt:
"Generate unit tests for this legacy function. Cover: normal cases, edge cases, error cases, and null/empty inputs. Use the xUnit framework and mock any external dependencies. Ensure tests are deterministic. Add comments explaining each test case."
Example: For a legacy C++ function with no tests, AI generated 30 tests that passed immediately, giving us confidence to refactor.
Why it works: AI can analyze the function's logic and create tests that document expected behavior, making refactoring safer.
8. The One-Liner Whisperer: Simplify Complex Expressions
Prompt:
"Simplify this complex expression (paste code) without changing its behavior. Use modern language features (e.g., optional chaining, null-coalescing, pattern matching) where appropriate. Show the diff and explain why the new version is clearer."
Example: A nested ternary in JavaScript was replaced with a switch statement and optional chaining, cutting lines from 15 to 6.
Why it works: AI can see the logic and apply language idioms, making the code more concise and readable.
9. Comment Cleanup: Remove Obsolete Comments
Prompt:
"Review comments in this file. Remove any that are misleading, redundant, or describe 'what' instead of 'why'. For any comment that explains non-obvious logic, keep it but rephrase for clarity. Output the file with updated comments and a list of removed comments."
Example: A codebase had comments like '// increment i' next to 'i++'. AI removed 80% of comments, leaving only the 'why' ones. This reduced visual noise and improved focus.
Why it works: AI can distinguish between useful intent comments and noise, but always manual review.
10. Duplicate Code Destroyer: Find and Merge
Prompt:
"Identify duplicated code blocks across this codebase (similar logic, variable names may differ). Group them by similarity and propose a unified function with parameters. Show the new function and the refactored call sites."
Example: In a Python Django project, AI found 5 different functions that all did the same date parsing. It merged them into one utility function, reducing bugs and maintenance.
Why it works: AI can detect near-duplicates that simple text search misses.
11. Error Handling Upgrade: Add Proper Exceptions
Prompt:
"Review this code's error handling. Replace bare 'catch (Exception)' or 'except:' with specific exception types. Add meaningful error messages that include context (e.g., variable values, operation). Ensure no error is silently swallowed. Show the before/after."
Example: A legacy VB.NET app was catching all exceptions and returning false. AI changed it to throw specific exceptions with message like 'Failed to save order 123: connection timeout'. This made debugging infinitely easier.
Why it works: AI understands exception hierarchies and can suggest appropriate types, but ensure it matches your logging strategy.
12. Security Patch in a Prompt: Find Vulnerabilities
Prompt:
"Scan this code for common security vulnerabilities: SQL injection, XSS, hardcoded credentials, unsafe deserialization, etc. Use OWASP Top 10 as a checklist. For each finding, show the vulnerable line and a fix using best practices (e.g., parameterized queries, output encoding)."
Example: AI found a SQL injection in a legacy PHP login form. It fixed it by using PDO prepared statements. The prompt also flagged a hardcoded API key, which we moved to environment variables.
Why it works: AI can spot patterns of insecure code, but always run a real security scanner (like OWASP ZAP) to confirm.
13. The Style Refactorer: Enforce Code Standards
Prompt:
"Refactor this code to match [linter/style guide] (e.g., PEP 8, ESLint). Fix formatting, naming conventions, and line lengths. Do not change the logic. Show a diff of the changes."
Example: A Python codebase had inconsistent indentation and naming. AI applied black and pylint fixes, making the code uniform and easier to review.
Why it works: AI can automate tedious style fixes, but be sure to run your linter to verify.
14. The API Evolution: Update to Modern Interfaces
Prompt:
"This code uses deprecated APIs (e.g., old libraries). Replace them with modern equivalents. List each replacement and the reasoning. Handle any breaking changes. Show the diff."
Example: A Java app used new URL(...).openConnection() and AI migrated it to HttpClient with proper timeouts, improving handleing of redirects and reduced boilerplate.
Why it works: AI stays up-to-date with library changes and can perform migrations that are too tedious for humans.
15. The Documentation Magician: Auto-generate README
Prompt:
"Generate a README for this project based on the code. Include: project overview, setup instructions, configuration, usage examples, and a summary of the architecture. Use a professional tone."
Example: A legacy project had no docs. AI generated a README that new hires found helpful, reducing onboarding time by days.
Why it works: AI can infer how to run and use the project from code and config files.
Putting It All Together
These prompts are not silver bullets. They work best when you have a clear goal and a test suite (even minimal). Remember, AI is a tool—always review its suggestions, especially for security and logic changes. Start with one prompt, measure the result, and iterate. Over time, you'll build a workflow that turns your legacy code from a liability into a reliable asset.
As you integrate AI into your refactoring process, you'll find that what used to take months can now be done in weeks. The key is to combine the AI's speed with your own judgment. So, which prompt will you try first?
Comments