All posts
prompt-engineeringrefactoringllm

Refactoring Prompts: Ready-to-Use Templates

Copy-paste refactoring prompts with real examples, plus what to change for your own use case.

SR

Suhail Roushan

August 6, 2026

·
6 min read
·
0 views

Every developer has stared at a tangled function and known it needs refactoring, but the prompt they write gets vague, generic advice back. These Refactoring Prompts give you copy-paste templates that force Claude, GPT-4, Gemini, or DeepSeek to produce specific, actionable changes instead of hand-waving suggestions. I've tested these across all four models, and they hold up consistently.

Why Generic Prompts Fail Here

The standard "refactor this code" prompt fails because it gives the LLM zero constraints. You get back a rewrite that changes your naming conventions, breaks your error handling, or introduces patterns your team has never used. The model optimizes for "clean code" in the abstract, not for your codebase's reality.

The failure mode is always the same: the LLM makes unilateral decisions about trade-offs you didn't ask about. It removes a guard clause you needed for legacy data, or it inlines a helper function that's used in three other files. These templates fix that by forcing the model to state its assumptions, preserve your constraints, and explain why each change matters.

Template 1: The Constraint-Locked Refactor

Use this when you have working code that's ugly but functional. The key is the "must preserve" section — it stops the model from breaking things you care about.

Refactor the following {language} code. 

Constraints:
- MUST preserve: {list of behaviors, APIs, or edge cases that cannot change}
- MUST NOT: {things the model should avoid, e.g., "change function signatures", "add dependencies"}
- MUST: {what you actually want, e.g., "reduce nesting depth", "extract duplicate logic"}

Here is the code:
```{language}
{PASTE YOUR CODE HERE}

Output format:

  1. A brief summary of what you changed and why (max 5 bullet points)
  2. The full refactored code
  3. A list of any trade-offs you made (e.g., "increased memory usage by X to reduce time complexity")

If any constraint cannot be satisfied, tell me before showing code.


**Placeholders explained:** `{language}` is obvious. `{list of behaviors}` is where you paste your test names, API contracts, or specific edge cases like "handles null input" or "works with empty arrays". `{things to avoid}` is critical — if you don't want a rewrite, say so. This template works because it makes the LLM check its work against your rules before it writes anything.

## Template 2: The Diff-First Refactor

This one is for larger refactors where you want to see the *plan* before the code. It's especially good for GPT-4 and Claude, which can reason about multi-step changes.

```text
I need to refactor {file/function name} in {language}. The current code is below.

Step 1: Identify the top 3 structural problems (e.g., god object, duplicated logic, unclear naming).
Step 2: For each problem, propose a specific refactoring pattern (e.g., Extract Method, Replace Conditional with Polymorphism).
Step 3: Show me a diff (using unified diff format) that implements ONLY the first problem. Do not touch anything else.
Step 4: After I approve, I'll ask you to proceed to the next problem.

Current code:
```{language}
{PASTE YOUR CODE HERE}

Rules:

  • Do NOT combine fixes. One diff per problem.
  • Do NOT reformat code that isn't part of the fix.
  • If you can't isolate a fix cleanly, say so and suggest a different pattern.

This template turns a one-shot refactor into a reviewable process. You can catch mistakes after each step instead of getting a 500-line rewrite that you have to diff against your original manually. The diff format forces precision — the model can't hand-wave around what it changed.

## Template 3: The Legacy-Code Rescue

Use this for the hardest case: code that's been in production for years, has no tests, and nobody fully understands. These prompts are for when you're scared to touch the code at all.

```text
This is legacy {language} code with no test coverage. I need to refactor it safely.

Context:
- This code runs in production. A bug here costs {describe the cost, e.g., "customer data loss"}.
- The original author is {gone / unknown / unavailable}.
- Business logic that MUST stay identical: {describe what the code does from a user's perspective, not implementation}.

Task:
1. First, write a list of behavioral invariants — things the code must always do, no matter what.
2. Then, write 5-10 unit test cases that verify those invariants. Output them in {testing framework} syntax.
3. Only after I confirm the tests pass on the current code, propose a refactor.
4. The refactor must keep every test green.

Here is the code:
```{language}
{PASTE YOUR CODE HERE}

If you find any invariants that contradict each other or seem impossible, flag them immediately.


This is the only template that starts with tests, not code changes. It forces the model to build a safety net before it touches anything. It works brilliantly with DeepSeek and Gemini, which are strong at reasoning about edge cases even when the code is a mess.

## How to Adapt These for Your Own Codebase

First, replace the placeholder text with your actual constraints — don't leave the braces in. Second, paste real code, not a simplified version. LLMs catch more issues when they see the actual error handling and type annotations.

Third, add your team's conventions to the "MUST NOT" section. If you use `camelCase` and hate `lodash`, say so. Fourth, for large files (300+ lines), refactor in chunks. The context window gets diluted by irrelevant code, and the model starts hallucinating relationships that don't exist.

Finally, always run the output through your linter and test suite before merging. These templates reduce bad refactors, but they don't eliminate the need for human review. I've seen GPT-4 produce syntactically perfect code that silently changed a `>=` to a `>`.

## Do These Prompts Work With Any LLM?

Yes, but with caveats. Claude and GPT-4 handle Template 1 and 2 best because they follow multi-step instructions reliably. Gemini is excellent with Template 3 — it's surprisingly good at finding edge cases in legacy code. DeepSeek works with all three, but you may need to repeat the output format request if it drifts.

The biggest difference is token discipline. GPT-4 tends to give verbose explanations; Claude is more concise; Gemini sometimes skips the diff format if you don't repeat it. If you use these with a weaker model, add "Be concise. No preamble." to the start.

The one adjustment that improves these prompts the most: always include the "If you can't satisfy a constraint, tell me before showing code" line. It converts silent failures into explicit ones, and that single change makes the output dramatically more trustworthy.

Related posts

Written by Suhail Roushan — Full-stack developer. More posts on AI, Next.js, and building products at suhailroushan.com/blog.

Get in touch