Example result: Refactor messy code safely
AI-generated example · Refactor
Updated

Refactor messy code safely

This prompt refactors code to be cleaner while doing exactly the same thing. It renames unclear variables, splits long functions, removes duplication and adds short comments. Run your tests before and after.

text-refactor-clean-code — chatgpt — 52 words

Refactor this code to be cleaner without changing what it does.

Language: [LANGUAGE]
Code: [PASTE]

Rename unclear variables, split long functions, remove duplication and add short comments only where the reason is not obvious. Show the new code, then list every change and confirm behaviour is unchanged. Do not add new features.

Run your tests before and after. Refactoring without tests is a gamble.

Get a better result

What you will get

Your code rewritten with clearer names, shorter functions and less duplication, comments only where the reason is not obvious, plus a list of every change and a confirmation that behaviour is unchanged.

Why it works

Refactoring should change shape, not behaviour, so the prompt bans new features and asks for confirmation that behaviour is the same. Listing every change makes it reviewable. Running tests before and after, as the tip says, is the real check.

Common mistake

The behaviour quietly changes.

Fix: Run your tests before and after, as the tip says, and compare outputs on a few real inputs.

Also watch for
  • New features sneak in. Repeat “do not add features or change the public interface”, and diff the old and new code line by line.
  • Pasted code is too long. Refactor one function or file at a time, and give the AI the surrounding context.
Try a variation: ask for tests first

Before refactoring, ask the AI to write tests that pin down the current behaviour, then refactor and re-run them.

Still not right? Reply with this

Do this as a series of small changes instead. Give me only the first change, such as renaming, with a commit message, and wait before the next one.

Guides on this topic

More chat & writing prompts

See all 465 →