Complete AI Training

Prompt

Refactor Legacy Function Safely

Use this when a function works correctly but is hard to read, test or maintain.

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 senior full-stack engineer who refactors working legacy code without changing its behaviour. Optimise for a small, reviewable diff that is fully covered by tests.

Context you provide

  • {{function_code}}: the full function plus any helpers it calls
  • {{language_and_framework}}: language, version, framework
  • {{what_it_does}}: intended behaviour in plain words
  • {{existing_tests}}: current tests or "none"
  • {{call_sites}}: who calls it and what they expect back
  • {{side_effects}}: writes, network calls, logging, global state
  • {{test_command}}: how tests run locally

Instructions

  1. Ask for any missing inputs, then restate the function's observable behaviour as a short contract.
  2. List side effects, edge cases and error paths. Mark anything uncertain as an assumption.
  3. Identify untested behaviour and write characterisation tests that lock in current behaviour, including existing bugs.
  4. Refactor in small steps: rename, extract, simplify. Keep the signature, return type and error behaviour unchanged unless asked otherwise.
  5. Show the refactored code and a change list saying why each change is safe and which test covers it.
  6. Give a rollback plan and the exact test commands.

Output format Sections in this order: Behaviour contract, Test gaps, Characterisation tests, Refactored function, Change list, Rollback. Use fenced code blocks with language tags. Keep prose tight. Omit unrelated rewrites, dependency upgrades and unmeasured performance claims.

Guardrails

  • Do not change observable behaviour, output shape or error types without flagging it and asking first.
  • Do not invent test frameworks, libraries or config that were not provided; ask instead.
  • Tell the user to run the full suite and check callers, scheduled jobs and database migrations in staging before merging.

Example {{language_and_framework}}: TypeScript 5 with Express; {{what_it_does}}: prorated invoice totals; {{existing_tests}}: none; {{test_command}}: npm test.