Software engineering

Refactor prompt

A copy-and-paste prompt for ChatGPT, Claude or Gemini that gets a professional refactor on the first try, plus the cheapest model that does it well.

What most people type

refactor this to be cleaner ```python def get_discount(user): if user['type'] == 'vip': if user['years'] > 5: return 0.25 else: return 0.15 else: if user['years'] > 5: return 0.1 else: return 0 ```

It works, but the AI has to guess your python version, so the first answer usually needs another round. The version below asks for exactly what a professional would deliver.

The better prompt

Refactor this Python function to be cleaner and more readable without changing its behavior.

```python
def get_discount(user):
    if user['type'] == 'vip':
        if user['years'] > 5:
            return 0.25
        else:
            return 0.15
    else:
        if user['years'] > 5:
            return 0.1
        else:
            return 0
```

Requirements:
- Keep the same inputs and return values for every case, including the strict "> 5" comparison.
- Python version: [Python version]. Keep the function name and signature unless a change is clearly better, and say so if you change them.
- Return the refactored code in one code block, then 2-3 short bullets explaining what you changed and why.
- If you offer an alternative style (for example, a lookup table vs. flat conditionals), show it briefly and say which you'd choose.
- Mention any edge cases in the original, such as missing keys or unknown user types, but don't change how they're handled unless I ask.

Replace the [brackets] with your details before you send it: 'type', 'years', Python version.

Why this version works

  • Added behavior-preserving requirement. Refactor must not alter discount results.
  • Specified output format. Code block plus short rationale avoids rambling.
  • Added Python version placeholder. Version affects idioms like match or dict usage.
  • Asked to flag edge cases only. Avoids silent behavior changes.

What a professional refactor prompt covers

  • Asks to keep the same behavior
  • Asks for the refactored code with brief reasons
  • Python version placeholder or no assumption

Best AI model for this prompt

This is a everyday task: small function refactor; simple but behavior must be preserved exactly. You don't need the most expensive model. The cheapest model at each company that handles it well:

CompanyModelPer usePer 1,000 uses
AnthropicClaude Sonnet 5.5$0.0035$3.45
OpenAIGPT-6.1 Terra$0.0017$1.73
GoogleGemini 3.8 Flashcheapest$0.0013$1.29

Pay-per-use list prices for this prompt and its expected answer (about 300 tokens). On a monthly chat plan, the same choice shows up as more messages before you hit your limit. See today's AI prices.

Refactor prompt for ChatGPT, Claude and Gemini (Software engineering) · PromptSaver