Refactor Code for Readability and Maintainability
Refactor any code for readability and maintainability without changing its behavior.
This prompt runs a focused readability-and-maintainability pass over code you paste in, with an explicit guardrail that behavior must not change. The five numbered goals — extracting duplicated logic, naming constants, self-documenting variables, flattening nesting, and adding comments only where intent is unclear — keep the model from rewriting your architecture or 'improving' things you didn't ask about. The required diff summary lets you review what changed and why before you trust it. Reach for it on working-but-messy code you've inherited or written in a hurry.
You are a senior software engineer doing a code quality pass. Refactor the code below without changing its behavior. Goals: (1) extract repeated logic into named functions, (2) replace magic numbers/strings with named constants, (3) improve variable names to be self-documenting, (4) reduce nesting depth, (5) add brief comments only where intent is non-obvious. Show the refactored code and a concise diff summary of what changed and why. CODE: [PASTE CODE]
What you can expect back
Refactored code:
TAX_RATES = {"A": 1.08, "B": 1.05}
def calculate_total_with_tax(orders):
total = 0
for item in orders:
rate = TAX_RATES.get(item["type"])
if rate is not None:
total += item["price"] * rate
return total
Diff summary:
- Renamed calc -> calculate_total_with_tax; o -> orders, t -> total, i -> item for clarity.
- Replaced magic numbers 1.08 / 1.05 with a TAX_RATES constant, removing the if/elif duplication.
- Note: assumes item keys are 'price' not 'p' — confirm field names match your data.
- Behavior preserved: same totals for type A and B; unknown types still contribute 0.Illustrative example — your results will vary by tool and inputs.
Get sharper results
- 01Paste enough surrounding context (imports, called helpers, type definitions) so the model doesn't rename or remove something another part of your codebase depends on.
- 02Tell it your language version and style guide up front (e.g. 'Python 3.11, follow PEP 8' or 'TypeScript strict mode') so the constants and naming match your conventions.
- 03Add 'do not add or remove any external dependencies' if you want to keep the refactor self-contained and reviewable.
- 04Ask it to flag any place where preserving behavior is impossible without a small risk, rather than silently changing logic — the diff summary is where that disclosure should live.
- 05Run your existing tests against the output before committing; if you have none, ask the model to also generate a few characterization tests that lock in current behavior.
Adapt it for your case
Add a sixth goal asking it to flag obvious inefficiencies (repeated lookups, unnecessary copies) without changing the public interface.
Ask it to also introduce type annotations or interfaces while keeping runtime behavior identical.
Tell it to produce only the diff summary and a readability score first, so you can decide which changes to apply before it rewrites anything.
Common questions
How do I know it didn't change behavior?
Read the diff summary, then run your test suite. For untested code, ask the model to generate characterization tests against the original so you can verify the refactor passes them.
Can I paste a whole file or just a function?
Either works, but include any helpers or constants the code references. Missing context is the main cause of refactors that accidentally break callers.
Why does it add so few comments?
By design — goal (5) limits comments to non-obvious intent. Self-documenting names are preferred over comments that restate what the code already says.
You may also need
Perform a Thorough Code Review on a Pull Request
Get a senior-engineer-style code review with categorized, file-referenced feedback.
Audit Code for Performance Bottlenecks
Identify performance bottlenecks in code and get ranked, impact-focused optimization suggestions.
Run a Security Review on Code
Get an OWASP-aligned security review with severity ratings and remediation snippets.
Design a Clean REST API for a New Resource
Get a complete REST endpoint design with shapes, errors, and idempotency notes.