Back to Prompt Library

Code Rewrite

A high-signal refactoring prompt for rewriting existing code with constraints, tests, and clear change tracking.

Reviewed: 2026-03-18

Use this when you already have working or partially working code and want the model to improve readability, performance, safety, or maintainability without changing behavior by accident.

Prompt Template

You are a senior {language} engineer.

Goal:
Rewrite the code below for {goal} without changing the intended behavior unless explicitly requested.

Context:
- Runtime/framework: {runtime}
- Constraints: {constraints}
- Must preserve: {must_preserve}
- Style preferences: {style_preferences}

Code:
```{language}
{code}
```

Return exactly:
1. A short diagnosis of the main issues.
2. The rewritten code in one fenced block.
3. A concise change log.
4. Follow-up tests or risks to check.

Customize the variables before using the template in production workflows.

Best for

  • Refactoring duplicated logic in a component or service
  • Adding comments and naming cleanup before a handoff
  • Optimizing a hot path while preserving public behavior

Expected output

  • Issue diagnosis before the rewrite
  • Single final code block
  • Clear explanation of what changed
  • Risks or tests still worth checking

Variables to customize

language

Primary language of the code

Example: TypeScript

goal

What kind of rewrite you need

Example: readability and error handling

runtime

Execution context or framework

Example: Next.js 16 server component

constraints

Hard constraints that should not be violated

Example: Do not add new dependencies

must_preserve

Behavior or API that must stay stable

Example: Existing function signature and output shape

style_preferences

Formatting or style conventions

Example: Prefer early returns and short helper functions

Optimization tips

  • Tell the model what must not change before you ask for improvements.
  • Name the runtime and framework so the rewrite matches your environment.
  • Ask for a test checklist if you plan to apply the patch directly.

Example use case

Refactor a React component with repeated fetch-state handling, but keep props and rendered behavior unchanged.

Expected result

The model consolidates repeated branches, keeps the same prop contract, and gives you a short regression checklist.

References