When to use it

Use this prompt when a file has grown hard to read, before adding a feature to messy code, or when you inherit a function that nobody wants to touch. It is meant for refactoring in the strict sense: changing the structure of the code without changing what it does. That makes it safer than a generic “clean up this code” request, which often mixes style changes with unrequested behavior changes.

How to customize it

  • [LANGUAGE] and the framework version keep suggestions idiomatic and avoid features your runtime does not support.
  • [PURPOSE] lets the model choose names that describe the domain instead of generic names like data or result.
  • [STYLE GUIDE] aligns the output with your linter so the diff is not full of formatting noise.
  • [PARTS THAT MUST NOT CHANGE] protects public interfaces, database queries or log formats that other systems depend on.
  • [PASTE CODE] works best with one module or a few related functions at a time.

Why it works

The explicit rule that behavior must stay identical, and the separate list for bugs, stop the model from quietly “improving” logic you did not ask it to touch. Asking for a summary first gives you a cheap check that the model understood the code before it rewrites anything.

Breaking the work into small named steps mirrors classic refactoring practice: each step is easy to review and easy to revert. The risk list points you to the subtle changes, such as iteration order or mutation, that tend to slip through review. Our guide on using AI coding assistants effectively covers how to review generated changes in general.

Tips and variations

  • Make sure you have tests before refactoring. If you do not, ask first: “Write characterization tests that capture the current behavior of this code.”
  • Apply the steps one commit at a time so a failing test points to a single change.
  • Add “Keep the diff under [N] lines” when you only want the most valuable improvements.
  • For performance-sensitive code, add “Do not introduce extra allocations or I/O.”
  • Run your linter and full test suite on the result; a refactor that looks right can still break an edge case.