💻 CodingAdvanced🔧 Cursor

Refactor a Legacy Function with Cursor Agent Mode

Has Cursor's agent restructure a complex function or file in clear stages — preserving external behavior exactly, explaining every change before you accept it.

prompt.txt
Refactor the following code in Agent mode, in this exact order:

1. First explain the problems in the current code (unclear naming, a function doing too many things, duplication, weak error handling, etc.)
2. Propose a refactoring plan before touching anything — a short bullet list
3. Execute the refactor while preserving external behavior exactly (same inputs produce same outputs) — no new features
4. If the change touches more than one file, list every file changed and why
5. Show me a final diff summary before I accept

Code or file/function name: [paste the code here, or write @filename to have it read from project indexing]

Additional context: [e.g. this function handles API requests; it's a React component duplicated across several pages]

Hard constraint: do not change the public function signature (name / inputs / outputs) unless I explicitly approve a breaking change.

Most of the time lost refactoring old code isn’t writing the new version — it’s working out what the current code actually does before you dare touch it. This prompt forces Cursor’s agent to explain and plan first, so you don’t end up with a change that looks clean but silently breaks behavior you depended on.

When to use it

  • A function has grown into something that does five jobs at once
  • You inherited code from another developer with no documentation
  • You’re about to add a feature to an old file and want it cleaned up first
  • The same logic keeps appearing in multiple places across the project

How to use it

  1. Open Agent mode with Cmd/Ctrl + I inside Cursor
  2. Paste the prompt, replacing the bracketed section with your code or an @ mention of the file
  3. Read the refactoring plan it proposes before approving execution
  4. Review the final diff carefully — the agent edits, but you own the acceptance

The tip that makes the difference

If your project has a .cursorrules file, add a rule describing your naming and structure preferences there. Refactors then come out consistent with the rest of the codebase on the first pass, instead of needing manual correction afterwards.