How to Refactor Code with AI
Refactor means improve the shape of the code without changing what it does. With AI, you ask for clarity and tests — not a surprise rewrite of the whole app.
In short: lock behaviour with tests first, ask for a small named improvement, compare the diff, re-run tests. Ban “while you’re at it” feature changes.
Why refactor with AI
Messy helpers slow every future change. AI is fast at renaming, extracting functions and simplifying nested loops. It is also eager to change behaviour. Tests are the seatbelt.
What a safe refactor request includes
- Goal: “extract slugify”, “rename for clarity”, “remove duplication” — one goal.
- Freeze behaviour: “do not change outputs; keep public names unless I say so.”
- Scope: one file or one function first.
- Proof: existing tests, or ask the AI to add characterisation tests before editing.
How a safe refactor flows
Example: messy process() → slugify_many()
Refactor the function below. Goal: clearer name, typed Python 3.12, use regex for slugify, skip None/blank. Do NOT change the idea of the outputs for normal strings. Add a short docstring. Return code only.
def process(d):
o = []
for x in d:
if x is not None and str(x).strip() != "":
s = str(x).strip().lower().replace(" ", "-")
while "--" in s:
s = s.replace("--", "-")
o.append(s)
return oafter.py (tested here)import re
_SLUG = re.compile(r"[^a-z0-9]+")
def slugify_many(values: list[object]) -> list[str]:
"""Turn each non-empty value into a simple URL slug."""
out: list[str] = []
for raw in values:
if raw is None:
continue
text = str(raw).strip().lower()
if not text:
continue
slug = _SLUG.sub("-", text).strip("-")
if slug:
out.append(slug)
return outtest_after.pyfrom after import slugify_many
def test_basic():
assert slugify_many(["Pune City", " ", None, "Nashik--Road"]) == [
"pune-city",
"nashik-road",
]cd code/refactor
python3 -m pytest -q
# -> 1 passedHow to refactor step by step
- Get a green baseline (or write tests that pin today’s behaviour).
- Ask for one improvement: rename, extract, simplify — not all three plus features.
- Read every changed line. Reject new dependencies you did not request.
- Re-run tests. If behaviour shifted, either fix the prompt or discard the diff.
- Commit the refactor alone so reviews stay easy.
| Safe ask | Risky ask |
|---|---|
| “Extract a helper; keep outputs the same” | “Clean this up and also add caching and a CLI” |
| “Rename locals for clarity” | “Modernise the whole package” |
| “Remove duplication in these two functions” | “Rewrite in another language” |
Settings tip
- Project rules: “Refactors must not change public behaviour without a new test.”
- In Cursor / Copilot Agent: point at files with @ and say “only these files”.
- Prefer a strong model for big design refactors; use inline/fast for rename-only work.
Try this yourself: refactor messy code safely with AI
Hello friends. A refactor makes code cleaner without changing what it does. So first we write tests that pass on the messy code, then we let the AI clean it, and the same tests must still pass. The student names and marks here are fictional practice data.
नमस्कार मित्रांनो. Refactor म्हणजे code काय करतो ते न बदलता code स्वच्छ करणं. म्हणून आधी आपण असे tests लिहू जे messy code वर pass होतात, मग AI ला code साफ करू देऊ, आणि तेच tests नंतरही pass झाले पाहिजेत. इथली student नावं आणि marks फक्त practice साठी आहेत.
नमस्कार दोस्तों. Refactor का मतलब है code क्या करता है वह बदले बिना code को साफ करना. इसलिए पहले हम ऐसे tests लिखेंगे जो messy code पर pass होते हैं, फिर AI से code साफ करवाएंगे, और वही tests बाद में भी pass होने चाहिए. यहाँ के student नाम और marks सिर्फ practice के लिए हैं.
Ravindra Bagale's Tip
Never ask the AI to refactor code that has no tests. Write or generate the tests first, run them on the old code, and only then start the refactor.
Ravindra Bagale's Tip – मराठी
Tests नसलेल्या code चा refactor AI कडून कधीच करून घेऊ नका. आधी tests लिहा, जुन्या code वर चालवा, आणि मगच refactor सुरू करा.
Ravindra Bagale's Tip – हिंदी
बिना tests वाले code का refactor AI से कभी मत करवाना. पहले tests लिखो, पुराने code पर चलाओ, और फिर ही refactor शुरू करो.
Python 3.13.5 and pytest 9.2.0. Use Python 3.10 or newer. Older Python versions print the traceback with fewer ^^^ marker lines, but the last line with the error type and message is the same.Your task: a fictional class report prints one line per student with the marks and a grade. Marks of 75 or more are Distinction, 60 or more are First class, 35 or more are Pass, and anything lower is Fail. The working code below repeats the same string building four times and hides the cut-off numbers inside if lines. First prove the current behaviour with tests, then ask an AI assistant to refactor it, and finally prove that the behaviour did not change.
Messy starter — save this exact text as report.py
"""Messy starter for the refactor exercise (fictional practice marks)."""
def summary(scores):
out = []
for s in scores:
if s["marks"] >= 75:
out.append(s["name"] + ": " + str(s["marks"]) + " - Distinction")
elif s["marks"] >= 60:
out.append(s["name"] + ": " + str(s["marks"]) + " - First class")
elif s["marks"] >= 35:
out.append(s["name"] + ": " + str(s["marks"]) + " - Pass")
else:
out.append(s["name"] + ": " + str(s["marks"]) + " - Fail")
return "\n".join(out)
Characterization tests — save this as test_report.py (these tests record what the code does today):
"""Characterization tests: they must pass before AND after the refactor."""
from report import summary
SAMPLE = [
{"name": "Student A", "marks": 82},
{"name": "Student B", "marks": 64},
{"name": "Student C", "marks": 35},
{"name": "Student D", "marks": 20},
]
def test_sample_output_is_unchanged():
assert summary(SAMPLE) == (
"Student A: 82 - Distinction\n"
"Student B: 64 - First class\n"
"Student C: 35 - Pass\n"
"Student D: 20 - Fail"
)
def test_exact_cutoffs():
rows = [{"name": "X", "marks": m} for m in (75, 74, 60, 59, 35, 34)]
lines = summary(rows).splitlines()
assert [line.split(" - ")[1] for line in lines] == [
"Distinction", "First class", "First class", "Pass", "Pass", "Fail",
]
def test_empty_list_gives_empty_text():
assert summary([]) == ""
def test_single_student():
assert summary([{"name": "Student E", "marks": 100}]) == "Student E: 100 - Distinction"
Prompt to give your AI assistant (Copilot Chat, ChatGPT, Claude, Gemini or any similar tool):
promptRefactor this Python function for readability without changing its behaviour.
The returned text must stay exactly the same for every input.
(paste the whole report.py file here)
Please:
1. Remove the repeated string building.
2. Move the grade cut-offs 75, 60 and 35 into one named constant.
3. Add a small helper function grade_for(marks).
4. Keep the function name summary and its one argument.
5. Do not add any library, and do not change my tests.
Explain each change in one short sentence.
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - Activate it: on macOS or Linux run
source .venv/bin/activate. In Windows Command Prompt run.venv\Scripts\activate.bat, and in Windows PowerShell run.venv\Scripts\Activate.ps1. - Install pytest inside the virtual environment:
python -m pip install pytest. - Save the messy starter as
report.pyand the tests astest_report.pyin the same folder. - Run the tests on the messy code first with
python -m pytest -q test_report.py. All 4 tests must pass before you change anything. - Send the prompt to your AI assistant and paste your real
report.pywhere the prompt says so. - Read the AI answer. Check that it still uses
>=for every cut-off and still joins the lines with"\n". - Replace the contents of
report.pywith the refactored code and save it. Do not edittest_report.py. - Run the same test command again. All 4 tests must still pass. If one fails, the refactor changed the behaviour, so reject it or ask the AI to fix only that difference.
Real output before the refactor (messy code):
terminalpython -m pytest -q test_report.py
.... [100%]
4 passed in 0.01s
Real output after the refactor (the time in seconds can be slightly different on your computer):
terminalpython -m pytest -q test_report.py
.... [100%]
4 passed in 0.00s
Quick manual check (this works the same before and after the refactor):
terminalpython -c "from report import summary; print(summary([{'name': 'Student A', 'marks': 82}, {'name': 'Student D', 'marks': 20}]))"
Student A: 82 - Distinction
Student D: 20 - Fail
Optional refactored report.py (try it yourself first)
Your AI assistant may choose different names or a different structure. Any version is fine if the same 4 tests pass and the code is easier to read.
report.py"""Refactored version: same behaviour, clearer structure (fictional practice marks)."""
GRADE_BANDS = ((75, "Distinction"), (60, "First class"), (35, "Pass"))
def grade_for(marks: int) -> str:
"""Return the grade label for one mark."""
for cutoff, label in GRADE_BANDS:
if marks >= cutoff:
return label
return "Fail"
def summary(scores: list[dict]) -> str:
"""Return one line per student, like 'Student A: 82 - Distinction'."""
return "\n".join(
f"{s['name']}: {s['marks']} - {grade_for(s['marks'])}" for s in scores
)
Troubleshooting this exercise
- Problem: the tests fail before you refactor anything. Fix: you probably changed the starter or the test file while copying, so copy both files again exactly.
- Error:
test_exact_cutoffsfails after the refactor. Fix: the AI used>instead of>=, which changes the grade for exactly 75, 60 or 35 marks. - Error:
KeyError: 'marks'. Fix: the AI renamed the dictionary keys, but the data still uses"name"and"marks", so change the keys back. - Error:
test_sample_output_is_unchangedfails with an extra line or space. Fix: the refactor changed the text format, so compare the AI version with the original line formatName: marks - Grade. - Error:
SyntaxErroron an f-string line in Python 3.10 or 3.11. Fix: those versions do not allow the same quote character inside and outside an f-string, so use single quotes inside, likef"{s['name']}".
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
Tests first, refactor second
A refactor must not change results
आधी tests, मग refactor
Refactor मध्ये result बदलायचा नाही
Quick quiz
1. What must stay the same in a refactor?
Observable behaviour (outputs and public contracts), unless you explicitly change them.
2. What do you do before editing?
Have tests green, or add characterisation tests.
3. Why commit refactors alone?
So you can revert cleanly and reviewers see one intent.
4. What is a risky prompt?
Mixing cleanup with new features in one request.
Save tokens and money
Small scope = fewer tokens and safer diffs. Do not ask five models to rewrite the same module. One good pass + tests is enough.