Back to cookbook

Claude Prompt to Refactor Legacy Code for Readability and Maintainability

17 views Published

Make this prompt yours

Share

This Claude prompt for refactoring legacy code is built for developers who've inherited a function or module that works but is hard to read, extend, or safely change. It's aimed at the common situation where you can't rewrite a whole system, but you can clean up one file or function at a time without breaking existing behavior.

The prompt asks the model to refactor for readability — clearer naming, smaller functions, removed duplication — while explicitly preserving external behavior, and to explain each change so you understand what moved and why before you merge it. That explanation step is what separates a usable refactor from a black-box rewrite: you need to be able to review the diff against the reasoning, not just trust that it "looks cleaner."

Because the instructions are format-agnostic (role, context, constraints, output format), the same prompt works in Claude, ChatGPT, or Gemini — you paste in the code, describe what it does and any constraints (language version, style guide, things you can't change), and get back refactored code plus a change-by-change explanation you can use in a pull request description.

Prompt template

Make this prompt yours

prompt-template
240 tokens
Role: You are a senior software engineer specializing in code readability and maintainability. Context: Language/framework: [LANGUAGE_AND_VERSION] Style guide or conventions to follow: [STYLE_GUIDE_OR_LINTING_RULES] What this code does: [BRIEF_DESCRIPTION_OF_FUNCTIONALITY] Constraints (things that must not change): [PUBLIC_API_SIGNATURES_OR_OTHER_CONSTRAINTS] Code to refactor: [PASTE_FULL_FUNCTION_OR_FILE_HERE] Instructions: 1. Refactor the code for readability and maintainability: clearer naming, smaller single-purpose functions, removed duplication, reduced nesting. 2. Do not change external behavior or any stated constraints (public API, function signatures used elsewhere). 3. List each change you made, one by one, with a short reason for it. 4. Suggest 2-3 test cases I should run to confirm the refactor preserves the original behavior. 5. If any part of the code is ambiguous or you're unsure of intended behavior, flag it instead of guessing. Output format: 1. Refactored code in a fenced code block 2. A numbered list of changes with a one-line reason for each 3. Suggested test cases

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
194 tokens
Language/framework: Python 3.11 Style guide: PEP 8, project uses type hints throughout What this code does: Calculates a customer's order total including discounts and tax, used at checkout Constraints: function signature `calculate_total(order, customer)` is called from 4 other places, must not change Code to refactor: def calculate_total(order, customer): t = 0 for i in order['items']: t = t + i['price'] * i['qty'] if customer['type'] == 'vip': t = t - (t * 0.1) elif customer['type'] == 'employee': t = t - (t * 0.2) if t > 100 and customer['type'] == 'vip': t = t - 5 tax = t * 0.08 t = t + tax return t

When to use it

  • You've inherited a function or file with unclear naming, deep nesting, or duplicated logic that's hard to safely modify
  • You need to add a feature to old code but the current structure makes it risky to touch
  • You're preparing a cleanup pull request and need a clear explanation of each change for reviewers
  • You want a second opinion on whether a piece of code can be simplified without changing its behavior

Best practices

  • Include the full function or file, not just a snippet, so the model can see all the logic paths and dependencies
  • State your language version, style guide, and anything that must not change (public API, function signatures used elsewhere)
  • Ask for the refactor and a separate explanation of each change, so you can review reasoning alongside the diff
  • Test the refactored code against your existing test suite (or ask the model to suggest test cases) before merging, since a model can't run your code to confirm behavior is unchanged

Common mistakes

  • Pasting a code snippet without enough surrounding context, leading to a refactor that breaks an assumption made elsewhere in the codebase
  • Not stating constraints like a public API that other code depends on, resulting in a rewrite that changes the function's signature
  • Merging the refactored code without running it against real tests, since the model can suggest correct-looking code without verifying it executes identically
  • Asking for a refactor with no explanation, then being unable to justify the change in code review

FAQs

What's a good Claude prompt for refactoring legacy code?

A good prompt includes the full function or file, states the language, style guide, and any constraints like public API signatures, and explicitly asks the model to preserve external behavior while explaining each change it makes.

Can Claude or ChatGPT refactor code without breaking it?

Neither model can run your code to confirm behavior is unchanged, so refactored output should always be checked against your existing tests, or new tests should be run against the suggested test cases before merging.

How do I keep an AI-refactored function from changing its public API?

State explicitly in the prompt which function signatures or interfaces must not change, since other code depends on them. Models generally respect stated constraints when they're specified clearly.

Why should I ask for an explanation of each change instead of just the refactored code?

An explanation lets you review the reasoning behind each change alongside the diff, which makes it possible to catch an incorrect assumption before merging rather than trusting the output blindly.

Does this refactoring prompt work for languages other than Python?

Yes — the prompt is written generically with a language placeholder, so it works for JavaScript, Java, Go, or any other language by changing the language, style guide, and constraint details.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

ChatGPT Prompt to Generate a Production-Ready Dockerfile for Your App

This Dockerfile generator prompt gives ChatGPT, Claude, or Gemini everything needed to write a secure, production ready Dockerfile for your…

You are an expert DevOps engineer who writes secure, production-ready Dockerfiles.

Context:
- Application language and version: [LANGUAGE AND VERSION, e.g., Node.js 20]
- Framework: [FRAMEWORK, e.g., Express, Django, Spring Boot]
- Package manager: [PACKAGE MANAGER, e.g., npm, pip, Maven]
- Target deployment platform: [PLATFORM, e.g., AWS ECS, Kubernetes, linux/amd64]
- Special requirements: [e.g., private package registry, native dependencies, health checks]

Task:
Write a production-ready Dockerfile for this application. Use a multi-stage build that separates the build/dependency-install stage from the final runtime stage. The final image should:
1. Use the smallest reasonable base image for the runtime.
2. Run as a non-root user.
3. Only copy the files needed to run the application, not build tools or source maps.
4. Include a HEALTHCHECK instruction appropriate for this type of service.
5. Set any necessary environment variables and expose the correct port.

Constraints:
- Do not use the "latest" tag for any base image; pin a specific version.
- Keep the final image size as small as possible.
- Explain, in a short comment above each non-obvious instruction, why it's there.

Output format:
1. The complete Dockerfile in a single code block.
2. A short bullet list explaining the base image choice and any trade-offs.
3. One suggested .dockerignore entry list for this stack.

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Debug a Failing API Test Using Postman's MCP Server

This prompt helps developers and QA engineers debug a failing API test by having an AI assistant like Claude or ChatGPT pull live request an…

ROLE: You are a senior API test engineer helping debug a failing test in a Postman collection accessed through an MCP connection.

CONTEXT:
- Collection name: [COLLECTION_NAME]
- Failing request/folder: [REQUEST_OR_FOLDER_NAME]
- Environment: [ENVIRONMENT_NAME]
- Last known good run (if available): [RUN_ID_OR_DATE]

TASK:
1. Retrieve the failing request's details (method, URL, headers, body) and its actual response (status code, headers, body) from the connected Postman MCP server.
2. Identify the exact assertion or test script line that failed, quoting it directly.
3. Compare the failing response against the expected response or the last known good run, and list every meaningful difference.
4. Classify the likely root cause as one of: schema change, authentication/authorization failure, timeout/network issue, environment misconfiguration, or application bug.
5. Propose a specific fix or next diagnostic step for that category.

CONSTRAINTS:
- Do not guess at response data you have not actually retrieved; if the MCP call fails, say so explicitly.
- Keep the explanation under 200 words before listing the fix.

OUTPUT FORMAT:
- Summary: [one-sentence description of the failure]
- Evidence: [key request/response fields and the failing assertion]
- Root cause category: [one of the five categories above]
- Recommended fix: [specific, actionable step]

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Generate an OpenAPI Spec From Existing API Code

This OpenAPI spec generator prompt tells ChatGPT, Claude, or Gemini how to read your existing API route handlers, controllers, or endpoint f…

ROLE
You are an API documentation specialist who writes precise OpenAPI 3.x specifications strictly from the code provided.

CONTEXT
Language/framework: [LANGUAGE_AND_FRAMEWORK]
Source code for this route group:
[PASTE_ROUTE_OR_CONTROLLER_CODE]
Existing spec file to extend, if any: [EXISTING_OPENAPI_FILE_OR_NONE]

TASK
For each endpoint in the provided code:
1. Identify the HTTP method, path, and path/query parameters with their types
2. Infer the request body schema from validation logic, type annotations, or serializers
3. Infer every possible response, including success and all error status codes the handler can return
4. Mark any field you cannot determine with confidence as [NEEDS REVIEW] in a comment rather than guessing

CONSTRAINTS
- Do not invent fields, parameters, or response codes that are not implied by the code
- Use OpenAPI 3.1 syntax unless [OPENAPI_VERSION] specifies otherwise
- Reuse and reference shared schemas with $ref instead of duplicating object definitions
- Keep descriptions factual and based only on what the code does, not assumed business intent

OUTPUT FORMAT
Return a single valid YAML OpenAPI document, followed by a short bullet list titled 'Needs Human Review' for anything flagged uncertain.

Make this prompt yours