Home · Prompts · Refactor Legacy Code
PROMPT

Refactor Legacy Code

Systematic prompt for modernizing legacy codebases incrementally without breaking existing functionality.

TARGET QUERY ai refactor code prompt · ~4K/mo
CATEGORY
Coding
DIFFICULTY
Advanced
BEST WITH
Claude Opus 4
UPDATED
2026-05-17
TAGS
refactoringlegacymodernizationtechnical-debt
PROMPT DETAILS Updated 2026-05-17

The Prompt

You are a refactoring specialist. I'll share legacy code that needs modernization. Follow this process:

**Phase 1 — Understand**
- What does this code actually do? (Ignore what comments claim)
- What are its inputs, outputs, and side effects?
- What implicit assumptions does it make?

**Phase 2 — Assess**
- Rate technical debt severity (1-10)
- Identify: dead code, duplications, god objects, tight coupling
- Flag anything that would break if refactored naively

**Phase 3 — Plan**
Propose a refactoring plan as numbered steps, where each step:
- Is independently deployable
- Has no behavior change (pure refactor)
- Includes a verification strategy

**Phase 4 — Execute**
Implement step 1. Show before/after with explanation.

Constraints: Maintain backward compatibility. No new dependencies without justification. Preserve all existing tests.

How To Use It

Paste a module or class that has accumulated technical debt. The phased approach prevents the common mistake of trying to rewrite everything at once, which invariably introduces regressions.

Why It Works

Legacy refactoring fails when developers change behavior and structure simultaneously. This prompt enforces the discipline of understanding first, then making one safe change at a time — the same approach used in “Working Effectively with Legacy Code.”

Variations

Extract and test:

This function is untestable because of its dependencies. Show me how to extract the pure logic into a testable function, leaving a thin wrapper for the I/O.

Modernize patterns:

Rewrite this using modern [language] idioms (async/await, pattern matching, etc.) but explain each change so I can verify it's behavior-preserving.

Dependency untangling:

This module has circular dependencies. Map the dependency graph, identify the cycle, and show me how to break it with dependency inversion.