Skip to content

Module 04 · Lesson 4.5

Reviewing AI-Proposed Refactorings

40 minUpdated 19 Nov 2026Part of Characterization Tests and Safe Refactoring · Existing Project Engineering
On this page
  1. What you will learn
  2. Why AI refactorings need a careful review
  3. Worked scenario: the assistant's tidy-up of price_order
  4. Step-by-step workflow: review a proposed refactoring
  5. What each test layer caught
  6. Recording the oddities and deciding them separately
  7. Asking an assistant for refactorings that are safer to review
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

Imagine you ask a helper to tidy your desk. They return it neat, and they also threw away a note that looked like rubbish. It was your only record of a phone number. The desk looks better, and something is lost.

An AI assistant can tidy code in the same way. Most of its changes are fine. One or two may change what the code does, and the code still looks clean. This lesson shows how to catch those changes with the tests you built, using the fictional Tidewell Wholesale price_order function. The people and data are invented.

What you will learn

  • Run the right checks before reading an assistant's diff.
  • Label each hunk of a diff as structure, behaviour or unsure.
  • Use failing characterization and golden master tests to find a behaviour change.
  • Keep the good hunks, drop the risky ones, and record odd behaviour for a separate decision.

Before you start

  • You have read Small, Reversible Refactorings.
  • You have passing characterization tests and, ideally, a golden master for the code.
  • You can read a unified diff.

Why AI refactorings need a careful review

An assistant writes code that looks neat. It is trained to make code that reads well. But reading well is not the same as behaving the same.

Old code often has odd rules that look like mistakes. An assistant sees an odd rule and 'helpfully' smooths it out. The new code is cleaner and different.

Behaviour change
Any change in what the code returns, saves or raises, for any input. A change you did not mean to make.
Hunk
One block of changed lines in a diff, starting with a line such as @@ -10,6 +10,7 @@. A diff is a list of hunks, like a list of edits on a page.
Tidy-up
A change meant only to make code neater. It should never change behaviour. Some do.

Where does behaviour hide? In small things that look like style.

Looks like styleCan change behaviour becauseExample in price_order
< becomes <=The exact boundary now goes the other way.An order of exactly £50.00 would start to pay delivery.
Lower-casing or trimming text before comparingValues that did not match now match.standard would start to pay delivery.
A new default valueCallers that omit the argument get a different result.A default band or account.
Raising an error for bad inputInput that used to work now fails.Rejecting a zero-quantity line.
Reordering operationsRounding or side effects can differ.Rounding VAT per line, not once at the end.
Swapping a loop for a built-inEdge cases such as an empty list can differ.sum of an empty order.
A short list of things to look at first in any diff.

Worked scenario: the assistant's tidy-up of price_order

You have refactored price_order in four small commits. A colleague suggests one more pass by an assistant: 'Tidy invoicing/totals.py and make it more robust.' The assistant answers (illustrative):

Notice the word 'otherwise'. The assistant admits to two behaviour changes in a friendly tone. Here is the diff it produced. The ZERO constant and the sum rewrite are fine. Find the other two.

git diff of the assistant's proposalCaptured from a real run
diff --git a/invoicing/totals.py b/invoicing/totals.py
index f1a1bf6..0ce471f 100644
--- a/invoicing/totals.py
+++ b/invoicing/totals.py
@@ -10,10 +10,11 @@ VOLUME_DISCOUNT_MULTIPLIER = Decimal("0.95")
 VAT_RATE = Decimal("0.20")
 PENNY = Decimal("0.01")
+ZERO = Decimal("0.00")
 
 
 def delivery_charge(goods, band):
-    if band == "Standard" and goods < FREE_DELIVERY_FROM:
+    if band.lower() == "standard" and goods <= FREE_DELIVERY_FROM:
         return DELIVERY_CHARGE
-    return Decimal("0.00")
+    return ZERO
 
 
@@ -26,10 +27,11 @@ def line_total(unit_price, qty, band):
 
 def price_order(lines, band, account="", get_list_price=list_price, get_discount=contract_discount):
-    goods = Decimal("0.00")
-    for sku, qty in lines:
-        unit_price = get_list_price(sku)
+    def unit_price_for(sku):
+        price = get_list_price(sku)
         if band == "Contract":
-            unit_price = contract_unit_price(unit_price, get_discount(account))
-        goods = goods + line_total(unit_price, qty, band)
+            price = contract_unit_price(price, get_discount(account))
+        return price
+
+    goods = sum((line_total(unit_price_for(sku), qty, band) for sku, qty in lines), ZERO)
     delivery = delivery_charge(goods, band)
     vat = ((goods + delivery) * VAT_RATE).quantize(PENNY, rounding=ROUND_HALF_UP)

The diff is the real result of applying the assistant's change to the scratch repository. The assistant's wording above is illustrative.

Before reading further, run the tests. This is the step people forget: tests first, because they are cheaper than careful reading.

pytest on the assistant's version (timings vary)Captured from a real run
.....F.......F.F                                                         [100%]
================================== FAILURES ===================================
_____ test_standard_delivery_is_charged_only_below_fifty_pounds[40-50.00] _____
tests\test_price_order_characterization.py:50: in test_standard_delivery_is_charged_only_below_fifty_pounds
    assert (str(result["goods"]), charged) == (expected_goods, qty < 40)
E   AssertionError: assert ('50.00', True) == ('50.00', False)
E     
E     At index 1 diff: True != False
E     Use -v to get more diff
___ test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR ____
tests\test_price_order_characterization.py:71: in test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR
    assert result["delivery"] == Decimal("0.00")
E   AssertionError: assert Decimal('7.50') == Decimal('0.00')
E    +  where Decimal('0.00') = Decimal('0.00')
________________ test_price_order_matches_the_approved_output _________________
price_order output no longer matches the approved file:
--- approved
+++ received
@@ -1 +1 @@
-01 Standard - [NAP-100x40] goods=50.00 delivery=0.00 vat=10.00 total=60.00
+01 Standard - [NAP-100x40] goods=50.00 delivery=7.50 vat=11.50 total=69.00
@@ -3 +3 @@
-03 standard - [NAP-100x39] goods=48.75 delivery=0.00 vat=9.75 total=58.50
+03 standard - [NAP-100x39] goods=48.75 delivery=7.50 vat=11.25 total=67.50
@@ -12 +12 @@
-12 standard - [NAP-100x15 STR-500x10 LID-250x13] goods=24.66 delivery=0.00 vat=4.93 total=29.59
+12 standard - [NAP-100x15 STR-500x10 LID-250x13] goods=24.66 delivery=7.50 vat=6.43 total=38.59
@@ -19 +19 @@
-19 standard - [NAP-100x17] goods=21.25 delivery=0.00 vat=4.25 total=25.50
+19 standard - [NAP-100x17] goods=21.25 delivery=7.50 vat=5.75 total=34.50
@@ -33 +33 @@
-33 standard - [CUP-250x44 LID-250x14 CUP-250x19] goods=12.32 delivery=0.00 vat=2.46 total=14.78
+33 standard - [CUP-250x44 LID-250x14 CUP-250x19] goods=12.32 delivery=7.50 vat=3.96 total=23.78
=========================== short test summary info ===========================
FAILED tests/test_price_order_characterization.py::test_standard_delivery_is_charged_only_below_fifty_pounds[40-50.00]
FAILED tests/test_price_order_characterization.py::test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR
FAILED tests/test_price_order_golden.py::test_price_order_matches_the_approved_output
3 failed, 13 passed in 0.05s

Three tests fail. Read what they say:

  • ..._only_below_fifty_pounds[40-50.00] failed. An order of exactly £50.00 now pays delivery. That is the < to <= change.
  • test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR failed. The lower-case band now pays £7.50. That is the .lower() change.
  • The golden master failed. Its diff lists five orders: order 01 (exactly £50.00) and four lower-case orders with goods under £50 (03, 12, 19 and 33). Each now has a delivery charge, so VAT and total changed too. Lower-case orders over £50 did not change, since they pay no delivery either way.

The tests found both changes in seconds. Without them, you would be hunting two quiet changes by eye.

Step-by-step workflow: review a proposed refactoring

  1. Step 1: Apply the proposal on a separate branch

    Do not apply it to your main working branch. A branch keeps the original safe and lets you throw the proposal away.

    What you should see: The proposal is in a branch you can delete.

  2. Step 2: Run all the tests before reading anything

    Run the characterization tests and the golden master. Red tests are your first and cheapest clues.

    Bash
    python -m pytest -q

    What you should see: A list of failing tests, or a green run.

  3. Step 3: Read the diff hunk by hunk and label each one

    Write one of three labels beside each hunk: structure (only moves or renames), behaviour (changes what the code does) or unsure. Look at the table of risky changes above.

    What you should see: Every hunk has a label.

  4. Step 4: Ask the assistant to list its behaviour changes

    Ask: 'List every change in this diff that could alter behaviour for any input, including edge cases.' Compare its list with yours. Treat its list as a second opinion, not proof.

    What you should see: A list that may find things you missed.

  5. Step 5: Resolve every 'unsure' with a test or an experiment

    Write a quick test for the input in doubt, run it on the old and the new code, and compare. If you cannot decide, drop the hunk.

    What you should see: No hunks left as 'unsure'.

  6. Step 6: Keep structure, drop behaviour

    Remove the behaviour hunks from the proposal and run the tests again. They must all pass.

    What you should see: A green run with only structure changes.

  7. Step 7: Record the oddities and decide them separately

    Write down each odd rule the assistant tried to smooth out. Behaviour changes, if wanted, are separate commits, with a decision from the owner.

    What you should see: A note and a list of questions for the owner.

Reviewing an assistant's refactoring
  1. Apply on a branch

    Keep the original safe

  2. Run all tests

    Characterization and golden master

  3. Label each hunk

    Structure, behaviour, unsure

  4. Resolve doubts

    A test, or drop it

  5. Keep structure only

    Tests green again

  6. Record oddities

    Decide separately

Tests come before reading, because they are fast and impartial.

What each test layer caught

Try each of the assistant's two risky changes alone. The results show why you want more than one kind of test.

Only the lower-case changeCaptured from a real run
-    if band == "Standard" and goods < FREE_DELIVERY_FROM:
+    if band.lower() == "standard" and goods < FREE_DELIVERY_FROM:
.............F.F                                                         [100%]
=========================== short test summary info ===========================
FAILED tests/test_price_order_characterization.py::test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR
FAILED tests/test_price_order_golden.py::test_price_order_matches_the_approved_output
2 failed, 14 passed in 0.03s
Only the boundary changeCaptured from a real run
-    if band == "Standard" and goods < FREE_DELIVERY_FROM:
+    if band == "Standard" and goods <= FREE_DELIVERY_FROM:
.....F.........F                                                         [100%]
=========================== short test summary info ===========================
FAILED tests/test_price_order_characterization.py::test_standard_delivery_is_charged_only_below_fifty_pounds[40-50.00]
FAILED tests/test_price_order_golden.py::test_price_order_matches_the_approved_output
2 failed, 14 passed in 0.02s

Each change was caught twice: once by a named characterization test and once by the golden master. The named test tells you which rule moved. The golden master tells you how many cases moved. That is the value of having both.

The version you keep

Remove the two behaviour hunks and keep the rest. The diff against your current code is now structure only.

git diff of the kept versionCaptured from a real run
diff --git a/invoicing/totals.py b/invoicing/totals.py
index f1a1bf6..9351023 100644
--- a/invoicing/totals.py
+++ b/invoicing/totals.py
@@ -11,2 +11,3 @@ VAT_RATE = Decimal("0.20")
 PENNY = Decimal("0.01")
+ZERO = Decimal("0.00")
 
@@ -16,3 +17,3 @@ def delivery_charge(goods, band):
         return DELIVERY_CHARGE
-    return Decimal("0.00")
+    return ZERO
 
@@ -27,8 +28,9 @@ def line_total(unit_price, qty, band):
 def price_order(lines, band, account="", get_list_price=list_price, get_discount=contract_discount):
-    goods = Decimal("0.00")
-    for sku, qty in lines:
-        unit_price = get_list_price(sku)
+    def unit_price_for(sku):
+        price = get_list_price(sku)
         if band == "Contract":
-            unit_price = contract_unit_price(unit_price, get_discount(account))
-        goods = goods + line_total(unit_price, qty, band)
+            price = contract_unit_price(price, get_discount(account))
+        return price
+
+    goods = sum((line_total(unit_price_for(sku), qty, band) for sku, qty in lines), ZERO)
     delivery = delivery_charge(goods, band)
pytest on the kept version (timings vary)Captured from a real run
................                                                         [100%]
16 passed in 0.02s

All 16 tests pass. Is this version better? That is a judgement call. The sum rewrite adds a nested function for little gain. A reviewer may reasonably reject it as churn. A tidy-up should earn its place.

Recording the oddities and deciding them separately

The assistant was not entirely wrong. Delivery charged by exact letter case is a strange rule. But changing it is a business decision, not a tidy-up.

  • Some customers may rely on free delivery by agreement.
  • Cleaning the old customer records may be a better fix than changing the code.
  • Changing the boundary changes what an order of exactly £50.00 costs. That is a price change.

So write the oddities down, and ask the person who owns the answer. Here is a short note you might commit.

Markdowndocs/pricing-oddities.md
# price_order: behaviour we pinned but did not change

Recorded 2026-11-19 against commit d8c655b. Pinned by tests.

## 1. A lower-case band pays no delivery charge
- What happens: delivery is charged only when band == "Standard" (exact case).
  A few old records store "standard", so those customers never pay delivery.
- Pinned by: test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR
  and 8 of the 60 orders in the golden master.
- Question for the finance systems contact: should "standard" pay delivery?
  Is free delivery for these accounts intended? How many records are affected?

## 2. A zero-quantity line is kept and priced at 0.00
- What happens: the line stays in the order and adds nothing.
- Pinned by: test_zero_quantity_line_is_kept_and_priced_at_zero_CURRENT_BEHAVIOUR.
- Question for the sales operations manager: should zero-quantity lines be rejected?
  Do EDI customers send them as placeholders?

## Not odd, but worth knowing
- Under the Volume rule, 19 units and 20 units cost the same, because 5% off
  20 units equals the price of 19.

An example note. Illustrative: it is not output from a run.

Decisions go to the roles who own them: the finance systems contact for delivery and prices, the sales operations manager for order rules. When a decision arrives, make the change in its own commit, update the tests on purpose, and re-approve the golden master with a reason. Planning a Small Change in the next module shows how to plan one.

Asking an assistant for refactorings that are safer to review

You cannot stop an assistant from being helpful. You can make helpfulness safer with the way you ask.

  • Narrow the task. 'Extract delivery_charge' beats 'tidy this file'.
  • Say what must not change. 'Preserve behaviour exactly, including odd cases. Do not make comparisons more robust.'
  • Ask for a diff only. Full rewritten files hide changes.
  • Ask for a list of behaviour changes. 'If any hunk could change behaviour for any input, list it.'
  • Run the tests yourself. Do not accept 'all tests pass' from the assistant.

The site's AI-Generated Code Review Checklist lists more things to check, and the blog post AI Code Review: Catching Bugs Before They Ship shows review prompts.

Conclusion and your next step

An assistant's tidy-up can change behaviour while it looks harmless. Run the tests first, label each hunk, resolve doubts with experiments, keep structure and drop behaviour. Record odd rules, and decide them separately with the people who own them.

Your next step: you now have the skills to change old code safely: pin it, isolate it and refactor it in small steps. Move on to Implementing Changes in an Existing Codebase to add a real feature, a minimum order value, with acceptance criteria, a feature flag and a reviewable pull request.

Further reading: see How to Prevent AI Hallucinations in Code Generation and the module overview Characterization Tests and Safe Refactoring.

Reusable prompt

Behaviour-change reviewer

Asks an assistant to compare the original code with a proposed refactoring and list every hunk that could change behaviour, as a second opinion for your own review.

Act as a strict reviewer. Below is the ORIGINAL code and a PROPOSED refactoring (a diff). The refactoring is supposed to keep behaviour exactly the same, including odd behaviour that tests pin on purpose.

Task:
1. Go hunk by hunk. For each hunk say: STRUCTURE (only moves or renames), BEHAVIOUR (could change the result for some input) or UNSURE.
2. For each BEHAVIOUR or UNSURE hunk, give one concrete input where old and new code would give different results, or say you cannot find one.
3. Do not suggest new improvements. Do not rewrite the code.
4. Say what you could not check because you could not see it.

Tests that currently pin behaviour (names only):
- test_standard_delivery_is_charged_only_below_fifty_pounds
- test_lowercase_standard_band_gets_no_delivery_charge_CURRENT_BEHAVIOUR
- test_zero_quantity_line_is_kept_and_priced_at_zero_CURRENT_BEHAVIOUR

Diff (synthetic code):
-    if band == "Standard" and goods < FREE_DELIVERY_FROM:
+    if band.lower() == "standard" and goods <= FREE_DELIVERY_FROM:
         return DELIVERY_CHARGE
-    return Decimal("0.00")
+    return ZERO
Show the reusable template

Replace each {{placeholder}} with your own details.

Act as a strict reviewer. Below is the ORIGINAL code and a PROPOSED refactoring (a diff). The refactoring is supposed to keep behaviour exactly the same, including odd behaviour that tests pin on purpose.

Task:
1. Go hunk by hunk. For each hunk say: STRUCTURE (only moves or renames), BEHAVIOUR (could change the result for some input) or UNSURE.
2. For each BEHAVIOUR or UNSURE hunk, give one concrete input where old and new code would give different results, or say you cannot find one.
3. Do not suggest new improvements. Do not rewrite the code.
4. Say what you could not check because you could not see it.

Tests that currently pin behaviour (names only):
{{test_names}}

Diff (code I am allowed to share):
{{diff}}

Expected output and limitations

A hunk-by-hunk list with a label for each, a concrete input for every behaviour hunk, and a short note on what the assistant could not see. It should not contain new suggestions or a rewritten function.

Sample responseIllustrative — your output will differ
Hunk 1: band == "Standard" -> band.lower() == "standard"   BEHAVIOUR
  Input where results differ: band "standard", goods 20.00.
  Old: delivery 0.00. New: delivery 7.50.
Hunk 2: goods < FREE_DELIVERY_FROM -> goods <= FREE_DELIVERY_FROM   BEHAVIOUR
  Input where results differ: band "Standard", goods exactly 50.00.
  Old: delivery 0.00. New: delivery 7.50.
Hunk 3: return Decimal("0.00") -> return ZERO   STRUCTURE
  Assuming ZERO is Decimal("0.00"). I cannot see where ZERO is defined.
Could not check: other callers of delivery_charge.

Limitations to keep in mind

  • The assistant can miss a behaviour change, or invent one. Use it as a second opinion only.
  • It cannot run your tests. Run them yourself.
  • It may be unable to see constants defined in other files, as in hunk 3.
  • This sample is illustrative. Real answers differ in wording and detail.

Common errors and how to fix them

The diff is read before the tests are run

Why it happens: The code looks clean and the changes look small.

Fix: Run the characterization tests and golden master first. A red test points at the hunk to read.

A behaviour change is accepted because the assistant called it a robustness improvement

Why it happens: Words like 'robust' and 'safer' sound harmless.

Fix: Ask: for which input does the result differ? If there is one, it is a behaviour change and needs a decision and a separate commit.

The approved file is re-approved to make the golden test pass

Why it happens: The new output looks plausible and the diff is long.

Fix: Do not re-approve a diff you did not intend. Drop the behaviour hunk and keep the approved file as it is.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Review an assistant's tidy-up of your own code

Ask an assistant to tidy the function you refactored earlier. Apply the result on a branch and review it using the workflow. Keep only the changes that preserve behaviour.

You will need

  • Your characterization tests and golden master, passing.
  • Permission to share the function with an assistant, or a synthetic copy.
  • A new branch.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If the assistant's tidy-up changes nothing risky, ask for a second one with 'make the comparisons more robust' to see what happens.
  • To test a doubtful hunk, write a tiny test for the input in question and run it on old and new code.
  • If tests stay green but a hunk worries you, drop it. You can always do it later with a test.
Show a model answer

A good answer shows tests run first, a labelled diff, a concrete input for each behaviour hunk, and a reduced diff that passes. The note shows the odd rules that were left alone, and who should decide. The log is honest: it admits the hunks that were kept only because a test proved them safe. A weak answer reads the diff once, accepts the assistant's claim that behaviour is unchanged, or re-approves the golden master to turn the run green.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.An assistant says its refactoring is 'otherwise behaviour-preserving' and lists one change it made for robustness. What do you do?
    Show the answer and explanation

    Answer: B. Robustness often means 'accepts input it used to reject' or 'treats values the same', which changes results. Honesty is welcome but not approval. Passing tests prove only what they cover, so you still need to look for an input that differs.

  2. 2.The golden master fails after an assistant's refactoring and the diff is long. What is the best response?
    Show the answer and explanation

    Answer: B. A failing master means behaviour changed. Re-approving records a possible accident as correct. Deleting the master throws away the wide net that caught the change.

  3. 3.You dropped the assistant's lower-case band change. Why not keep it, since the old rule looks like a mistake?
    Show the answer and explanation

    Answer: B. The rule may be a mistake or a hidden agreement. Only the owner can say. The assistant is often right about style, so the first option is wrong. Tests can be updated when a decision is made, so the third option is wrong too.

Frequently asked questions

Why does an assistant change behaviour when I only asked it to tidy?

It tries to make code cleaner and safer by common habits, such as comparing text without letter case. It does not know which odd rules your customers rely on. So it can smooth out a rule you needed.

Are passing tests enough to accept a refactoring?

They are necessary, not sufficient. Tests protect only what they cover. Read the diff too, label each hunk, and check any doubtful input with a quick test.

Should I ask the assistant to review its own work?

It can be a useful second opinion, especially to list behaviour changes. But it can miss things, so do not treat it as proof. The tests and your own reading come first.

What do I do with the odd behaviour I find?

Pin it with a test, write it in a note, and ask the person who owns the rule. If they want it changed, make that change in a separate, labelled commit and update the tests on purpose.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.