Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

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

WHY

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

WHAT
  • 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

1 · Tests green or add characterisation tests 2 · One refactor goal name it clearly 3 · Review the diff reject behaviour changes 4 · Re-run tests must stay green 5 · Commit small easy to revert

Example: messy process() → slugify_many()

REFACTOR PROMPT (COPY)

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.

before.py
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 o
after.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 out
test_after.py
from 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 passed

How to refactor step by step

HOW
  1. Get a green baseline (or write tests that pin today’s behaviour).
  2. Ask for one improvement: rename, extract, simplify — not all three plus features.
  3. Read every changed line. Reject new dependencies you did not request.
  4. Re-run tests. If behaviour shifted, either fix the prompt or discard the diff.
  5. Commit the refactor alone so reviews stay easy.
Safe askRisky 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”
Rule: Agent mode can touch many files. Use Plan mode first, or limit the agent to listed paths. Keep shell approval on.

Settings tip

  1. Project rules: “Refactors must not change public behaviour without a new test.”
  2. In Cursor / Copilot Agent: point at files with @ and say “only these files”.
  3. 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.

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.

Environment (tested): this exercise was run on 6 November 2026 with 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

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):

test_report.py
"""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):

prompt
Refactor 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.
HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. 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.
  4. Install pytest inside the virtual environment: python -m pip install pytest.
  5. Save the messy starter as report.py and the tests as test_report.py in the same folder.
  6. 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.
  7. Send the prompt to your AI assistant and paste your real report.py where the prompt says so.
  8. Read the AI answer. Check that it still uses >= for every cut-off and still joins the lines with "\n".
  9. Replace the contents of report.py with the refactored code and save it. Do not edit test_report.py.
  10. 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):

terminal
python -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):

terminal
python -m pytest -q test_report.py
....                                                                     [100%]
4 passed in 0.00s

Quick manual check (this works the same before and after the refactor):

terminal
python -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

HOW
  1. 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.
  2. Error: test_exact_cutoffs fails after the refactor. Fix: the AI used > instead of >=, which changes the grade for exactly 75, 60 or 35 marks.
  3. Error: KeyError: 'marks'. Fix: the AI renamed the dictionary keys, but the data still uses "name" and "marks", so change the keys back.
  4. Error: test_sample_output_is_unchanged fails with an extra line or space. Fix: the refactor changed the text format, so compare the AI version with the original line format Name: marks - Grade.
  5. Error: SyntaxError on 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, like f"{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.

PRACTICE CARDAI Coding

Tests first, refactor second

Before you ask an AI to clean up code, write tests that pass on the current messy code.
These tests record today's behaviour, so they tell you at once if the refactor changed any result.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

A refactor must not change results

A good refactor gives the same output for every input, and only the code becomes easier to read.
If even one old test fails after the refactor, reject the change or ask the AI to fix only that difference.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

आधी tests, मग refactor

AI कडून code साफ करून घेण्याआधी, सध्याच्या messy code वर pass होणारे tests लिहा.
हे tests आजचं behaviour लक्षात ठेवतात, त्यामुळे refactor ने काही result बदलला तर लगेच कळतं.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Refactor मध्ये result बदलायचा नाही

चांगल्या refactor नंतर प्रत्येक input साठी output तसाच राहतो, फक्त code वाचायला सोपा होतो.
Refactor नंतर एक जरी जुनी test fail झाली, तर तो बदल नाकारा किंवा AI ला फक्त तेवढाच फरक दुरुस्त करायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding
Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.

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

SMART AI USE

Small scope = fewer tokens and safer diffs. Do not ask five models to rewrite the same module. One good pass + tests is enough.

Save these cards

INTERVIEW CARDAI Coding

How do you refactor with AI safely?

Tests first, one goal, review the diff.
Re-run tests; no surprise features.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Refactor vs rewrite

Refactor: same behaviour, clearer shape.
Rewrite: new design — needs new tests and a plan.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Refactor in 3

Green tests.
One named goal.
Diff + re-test.
Ravindra Bagale · ravindrabagale.com/ai-coding