title: "Refactoring Prompt Template" tested_with: claude-code: "1.0.x" codex-cli: "0.2.x" last_updated: 2026-03-21 status: proven difficulty: intermediate prerequisites: [03-prompting-for-agents]
Refactoring Prompt Template
When to Use This Prompt
When restructuring existing code without changing its external behavior.
The Prompt
Refactor [file or function] to [goal — e.g., "reduce duplication", "improve readability", "extract into separate module"].
Constraints:
- Don't change the public API / function signatures
- Keep all existing tests passing
- Run tests after refactoring to verify
# Adapt this by:
# - Be specific about the goal — "refactor" alone is too vague
# - The constraint about public API prevents breaking callers
# - Always include the test verification step
Why It Works
- Goal-oriented: Names exactly what improvement to make
- Constrained: Explicitly preserves external behavior
- Verified: Tests confirm nothing broke
Variations
Extract pattern:
The logic in [file] from lines [X] to [Y] is duplicated in [other file]. Extract it into a shared utility in [target location] and update both callers.
Simplification:
[function] is hard to read because [reason — e.g., "deeply nested conditions", "too many parameters"]. Simplify it without changing behavior. Run tests after.
Module split:
[file] has grown too large ([X] lines). Split it into focused modules:
- [module A] for [responsibility]
- [module B] for [responsibility]
Keep the public exports the same so callers don't need to change.
Example Output
The agent should: read the code, explain its refactoring plan, make changes, and run tests. If tests fail after refactoring, the agent should fix the issues — not skip the tests.