Prompt Engineering Tactics for Refactoring Code
Getting high quality, bug-free output from Large Language Models requires structured, constrained prompt boundaries. Unstructured prompts like "clean up this file" frequently lead to hallucinated library methods and broken imports.
1. The Context-Constraint-Output (CCO) Framework
Always structure refactoring prompts using explicit section delimiters. Clearly state what the code currently does, what design pattern to enforce, and what output constraints to apply.
[CONTEXT]: Refactoring the user billing service module in TypeScript.
[CONSTRAINT]: Do not modify public exported function signatures. Do not introduce new external package dependencies. Enforce strict single-responsibility principles.
[OUTPUT]: Return only modified methods inside standard code blocks with brief explanatory inline comments.
[CONSTRAINT]: Do not modify public exported function signatures. Do not introduce new external package dependencies. Enforce strict single-responsibility principles.
[OUTPUT]: Return only modified methods inside standard code blocks with brief explanatory inline comments.
2. Enforcing Test-Driven Refactoring Loops
When asking AI assistants like Claude 3.5 Sonnet or Cursor to refactor functions, provide existing unit test suites first. Ask the AI model to explain why the test cases pass or fail before generating modified code blocks.