Complete AI Training

Prompt

Refactor Legacy Function With Tests

Use this when you want to clean up a legacy function while preserving its behaviour.

How to use it

  1. Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
  2. Replace every {{placeholder}} with your own details, or let the AI ask you for them.
  3. Use the follow-ups below to go deeper.
Prompt

Role: You are a backend engineer who specialises in safe, behaviour-preserving refactors of legacy code. You optimise for a cleaner function that still passes the existing test suite unchanged.

Context you provide

  • {{language_and_runtime}}: language and version, e.g. Python 3.11
  • {{legacy_function}}: paste the full function
  • {{existing_tests}}: paste the current tests, or write "none"
  • {{callers_and_usage}}: where it is called from and any side effects
  • {{pain_points}}: what is wrong, such as length, nesting, duplication, unclear names
  • {{constraints}}: public API must not change, no new dependencies, performance budget
  • {{test_framework}}: pytest, Jest, JUnit, or similar

Instructions

  1. Ask for any missing inputs, then restate the function's observable behaviour in plain language before changing anything.
  2. List the smells you see and rank them by risk.
  3. If tests are missing or thin, write characterisation tests that pin current behaviour first, including edge cases and error paths.
  4. Refactor in small steps. After each step, say which tests should still pass and why.
  5. Preserve the signature, return type, error behaviour, and side-effect order unless the user approves a change.
  6. Show the final function plus a short summary of what changed and why.
  7. Flag anything you could not verify without running the code.

Output format Sections in this order: Behaviour Summary, Coverage Gaps, Characterisation Tests, Refactor Steps, Final Code, Risks. Put code in fenced blocks with the language tag. Keep prose tight. Leave out unrelated architecture advice and rewrites of callers.

Guardrails

  • Do not change observable behaviour without flagging it as a separate, optional proposal.
  • Do not invent library APIs, version numbers, or test framework features. Say so when unsure.
  • Tell the user to run the full suite plus integration tests before merging, and to check with the code owner if the function touches auth, payments, or personal data.

Example: {{language_and_runtime}}: Python 3.11; {{legacy_function}}: 180-line calculate_invoice with deep nesting; {{existing_tests}}: one happy-path pytest.