# Refactoring interview: a routine and 4 traps

> Refactoring interview prep: a five-step routine and a mock round run on 7 Python builds. Four plausible edits pass 3 tests but not 8; one breaks only on 3.12+.

- Canonical HTML: [https://unrust.dev/blog/refactoring-interview](https://unrust.dev/blog/refactoring-interview)
- Markdown representation: [https://unrust.dev/blog/refactoring-interview/index.md](https://unrust.dev/blog/refactoring-interview/index.md)

Published: 2026-11-27. By the Unrust team.

## What is a refactoring interview, and how do you prepare for one?

A refactoring interview usually hands you working but messy code and asks you to improve its structure without changing what it does; formats vary. Prepare with one routine: ask what must not change, pin the current behavior with tests, change one thing at a time, park the bugs you notice, and stop on green.

Ask the recruiter what your round includes: the language, whether you work in your own editor, whether tests exist or you must write them, and whether AI tools or a web search are allowed. This post describes no company's round and promises no interview result.

Below you get the routine as a table, a refactoring coding challenge we wrote for this post (a 27-line Python function and eight tests), the four plausible edits that break it, the same traps in JavaScript, and a way to score your own practice. For a Python refactoring interview, rehearse the routine on code you did not write, with the AI and autocomplete off.

We ran every Python program here on seven CPython builds (3.9.25, 3.10.21, 3.11.2, 3.12.16, 3.13.15, 3.14.7 and 3.15.2) and the JavaScript probes on three Node.js builds (18.20.4, 22.11.0 and 24.11.0) on November 27, 2026. The output shown comes from CPython 3.12.16 and Node.js 24.11.0, with the folder shown as /app and the time on each Ran 8 tests line normalized to 0.001s.

Tracebacks differ by build in decoration only: 3.9 and 3.10 name just the class in each test header, and 3.13 and later print a marker line under the failing code. Where results differ, the text says so.

## What does refactoring mean?

Refactoring means changing the internal structure of code to make it easier to understand and cheaper to modify without changing its observable behavior, in Martin Fowler's definition. In an interview, observable behavior is whatever callers and tests can see: return values, rounding, defaults and errors.

Michael Feathers calls tests that record what code does today characterization tests, and his 2016 post says they let you find out immediately whether you have changed behavior. The eight tests in the mock round are of that kind: they pin what the code returns today, including rules you might call bugs.

That is also the difference from a rewrite. A rewrite may change what the code returns; a refactor must not, and the tests are how you know.

## What are the five steps of a refactoring interview routine?

Five steps: scope what must not change, pin the behavior with tests, change one thing per run, park every bug you notice, and stop when the suite is green and the goal is met. The order is our suggestion, not a standard, and the table pairs each step with the question it answers.

Step 3 repeats until you stop, with a rerun of every test after each change. In the mock round below, five small changes took six runs of the full suite: the first run plus one rerun after each change.

The routine is for changing code without changing results. Our debugging interview post has a different routine for finding a bug, and the two share one habit: rerun everything.

```text
Step     Do                                                    Question it answers
-------  ----------------------------------------------------  --------------------------------------------------
1 Scope  Ask what must not change: results, rounding, errors   What may I touch, and what is off limits?
2 Pin    Run the tests; add one per odd branch you will touch  What would tell me I changed behavior?
3 Step   Make one small change, then rerun every test          Did that one change keep every result?
4 Park   Write down each bug or doubt; do not fix it now       What belongs in a separate change?
5 Stop   Stop when the goal is met and the suite is green      Is the structure better and the behavior the same?
```

## What should you do first in a refactoring interview?

Ask what must not change, run the tests that exist, and add a test for every odd branch you plan to touch: zero and negative quantities, rounding ties, floors and defaults. A refactor is only as safe as the behavior you have pinned, so pin it before you edit a line.

Our mock round is written for this post, not taken from any company's round. The prompt: this function works as far as anyone knows, so make it easier to change without changing what it returns.

The function skips lines with a quantity of 0 or less, takes 10 percent off a book line from three copies, adds 20 percent to every kind except books and food, applies one coupon (SAVE10 or SAVE5), takes 5 percent off for members, floors the total at zero and adds shipping last. You start with three happy-path tests for books, other kinds and coupons.

Predict before you open the answer: which behaviors would you pin before touching it, and what does the first run of the tests print?

```python
def order_total(lines, coupon=None, region="UK", member=False):
    total = 0
    for i in range(len(lines)):
        line = lines[i]
        if line["qty"] > 0:
            amount = line["price"] * line["qty"]
            if line["kind"] == "book":
                if line["qty"] >= 3:
                    amount = amount * 0.9
            elif line["kind"] != "food":
                amount = amount * 1.2
            total = total + amount
    if coupon == "SAVE10":
        total = total - total * 0.1
    elif coupon == "SAVE5":
        total = total - 5
    if member == True:
        total = total - total * 0.05
    if total < 0:
        total = 0
    if region == "IE":
        shipping = 0
    elif region == "UK":
        shipping = 5
    else:
        shipping = 9
    return round(total + shipping, 2)
```

### Answer and explanation

Pin the branches where a tidy-up could change a number: lines with a quantity of 0 or less, the member discount coming after the coupon, each region's shipping, a coupon bigger than the order (the total stops at zero and shipping is still charged), and a total that lands on a half cent. Those are the five added tests; the three happy-path tests are the first, second and fourth in the file.

The first run prints eight dots and OK, because the tests record what the code does today. They are characterization tests: if a later change turns one red, you changed behavior, whether or not you meant to.

```python
# test_orders.py
import unittest

from orders import order_total

GADGET = [{"kind": "gadget", "price": 50.0, "qty": 1}]
FOOD = [{"kind": "food", "price": 2.5, "qty": 2}]
CHEAP = [{"kind": "food", "price": 2.0, "qty": 1}]
TIE = [
    {"kind": "book", "price": 2.01, "qty": 3},
    {"kind": "gadget", "price": 1.34, "qty": 1},
    {"kind": "food", "price": 5.14, "qty": 1},
]


class OrderTotalTests(unittest.TestCase):
    def test_books_get_ten_percent_off_from_three(self):
        self.assertEqual(order_total([{"kind": "book", "price": 10.0, "qty": 2}]), 25.0)
        self.assertEqual(order_total([{"kind": "book", "price": 10.0, "qty": 3}]), 32.0)

    def test_other_kinds_add_twenty_percent(self):
        self.assertEqual(order_total(GADGET), 65.0)
        self.assertEqual(order_total(FOOD), 10.0)

    def test_lines_with_zero_or_negative_qty_are_skipped(self):
        lines = FOOD + [
            {"kind": "food", "price": 9.0, "qty": 0},
            {"kind": "food", "price": 9.0, "qty": -1},
        ]
        self.assertEqual(order_total(lines), 10.0)

    def test_coupons(self):
        self.assertEqual(order_total(GADGET, coupon="SAVE10"), 59.0)
        self.assertEqual(order_total(GADGET, coupon="SAVE5"), 60.0)
        self.assertEqual(order_total(GADGET, coupon="NOPE"), 65.0)

    def test_member_discount_comes_after_the_coupon(self):
        self.assertEqual(order_total(GADGET, coupon="SAVE10", member=True), 56.3)

    def test_shipping_by_region(self):
        self.assertEqual(order_total(FOOD, region="IE"), 5.0)
        self.assertEqual(order_total(FOOD, region="UK"), 10.0)
        self.assertEqual(order_total(FOOD, region="US"), 14.0)

    def test_a_coupon_bigger_than_the_order_stops_at_zero_and_shipping_is_still_charged(self):
        self.assertEqual(order_total(CHEAP, coupon="SAVE5", region="UK"), 5.0)

    def test_cents_come_from_the_running_total(self):
        self.assertEqual(order_total(TIE), 17.18)


if __name__ == "__main__":
    unittest.main()

$ python3 -m unittest
........
----------------------------------------------------------------------
Ran 8 tests in 0.001s

OK
```

## How do you refactor the mock round in five small changes?

Make five small changes and rerun every test after each: name the numbers, extract the line amount, extract the coupon, replace the shipping chain with a lookup, and replace the floor with max(). After every change, all eight tests and all three happy-path tests passed on all seven CPython builds.

The payoff is concrete: a new bulk threshold is one constant, a new region is one dictionary entry, and the line amount and the coupon each have their own function. The file grew from 27 to 39 lines, so refactoring is not the same as shortening.

Try the five changes on the original yourself, rerunning all eight tests after each, then open the answer to compare with our final code.

```text
State  Change                                                 Lines  8 tests           3 tests
-----  -----------------------------------------------------  -----  ----------------  ----------------
s0     the code as handed over                                27     7 of 7 builds OK  7 of 7 builds OK
s1     name six numbers as constants, such as MARKUP = 1.2    35     7 of 7 builds OK  7 of 7 builds OK
s2     extract line_amount(line); loop over lines directly    38     7 of 7 builds OK  7 of 7 builds OK
s3     extract apply_coupon(total, coupon)                    43     7 of 7 builds OK  7 of 7 builds OK
s4     the shipping if/elif chain becomes a SHIPPING lookup   40     7 of 7 builds OK  7 of 7 builds OK
s5     if total < 0: total = 0 becomes total = max(total, 0)  39     7 of 7 builds OK  7 of 7 builds OK
```

### Answer and explanation

Our final code reads as the pricing rules in order: add up the line amounts, apply the coupon, take the member discount, floor at zero, add shipping, round once. It is 39 lines against the original 27.

Three things stayed as handed over on purpose: member == True, float arithmetic with a single round at the end, and the silent skip of lines with a quantity of 0 or less. They are the first items on the park list below.

```text
# orders.py after step 5 (s5)
BULK_QTY = 3
BULK_FACTOR = 0.9
MARKUP = 1.2
COUPON_RATE = 0.1
COUPON_FLAT = 5
MEMBER_RATE = 0.05
SHIPPING = {"IE": 0, "UK": 5}
DEFAULT_SHIPPING = 9


def line_amount(line):
    amount = line["price"] * line["qty"]
    if line["kind"] == "book":
        if line["qty"] >= BULK_QTY:
            amount = amount * BULK_FACTOR
    elif line["kind"] != "food":
        amount = amount * MARKUP
    return amount


def apply_coupon(total, coupon):
    if coupon == "SAVE10":
        return total - total * COUPON_RATE
    if coupon == "SAVE5":
        return total - COUPON_FLAT
    return total


def order_total(lines, coupon=None, region="UK", member=False):
    total = 0
    for line in lines:
        if line["qty"] > 0:
            total = total + line_amount(line)
    total = apply_coupon(total, coupon)
    if member == True:
        total = total - total * MEMBER_RATE
    total = max(total, 0)
    shipping = SHIPPING.get(region, DEFAULT_SHIPPING)
    return round(total + shipping, 2)
```

## Which four edits look safe in a refactoring interview and are not?

Four plausible small edits to the finished code pass the three happy-path tests: an or default on shipping, a truthy check on quantity, a floor applied after shipping, and sum() in place of a running total. The full suite catches each one with a single failing test, and it catches sum() only on Python 3.12 and later.

These are the four traps of the title. Read each edit as a reviewer would: the or default treats a free shipping rate of 0 as missing, the truthy check lets a quantity of -1 through, the late floor lets a coupon eat into the shipping charge, and sum() adds floats differently on newer Pythons.

Predict before you open the answer: which of the four does the full suite catch on every build, and which does it catch only on some?

```text
# four edits to s5, shown as diffs against orders.py (- removed, + added, two spaces unchanged)

# 1 or_default
      total = max(total, 0)
-     shipping = SHIPPING.get(region, DEFAULT_SHIPPING)
+     shipping = SHIPPING.get(region) or DEFAULT_SHIPPING
      return round(total + shipping, 2)

# 2 truthy_qty
      for line in lines:
-         if line["qty"] > 0:
+         if line["qty"]:
              total = total + line_amount(line)

# 3 floor_after_shipping
          total = total - total * MEMBER_RATE
-     total = max(total, 0)
      shipping = SHIPPING.get(region, DEFAULT_SHIPPING)
-     return round(total + shipping, 2)
+     return round(max(total + shipping, 0), 2)

# 4 sum_builtin
  def order_total(lines, coupon=None, region="UK", member=False):
-     total = 0
-     for line in lines:
-         if line["qty"] > 0:
-             total = total + line_amount(line)
+     total = sum(line_amount(line) for line in lines if line["qty"] > 0)
      total = apply_coupon(total, coupon)
```

### Answer and explanation

The full suite catches the first three edits on all seven builds. It catches sum() on 3.12.16, 3.13.15, 3.14.7 and 3.15.2 only: on 3.9.25, 3.10.21 and 3.11.2 all eight tests pass, so the same refactor is safe on one Python and not on another.

The three happy-path tests pass all four edits on every build, which is the point of pinning the odd branches: a green suite proves only what it pins. The second table shows which added test catches which edit.

```text
# every edit on each build, against the 3 happy-path tests and the 8-test suite
Edit                  Builds        3 tests  8 tests  Assertion that fails
--------------------  ------------  -------  -------  ------------------------------
or_default            all 7         OK       FAILED   AssertionError: 14.0 != 5.0
truthy_qty            all 7         OK       FAILED   AssertionError: 5 != 10.0
floor_after_shipping  all 7         OK       FAILED   AssertionError: 2.0 != 5.0
sum_builtin           3.9 to 3.11   OK       OK       -
sum_builtin           3.12 to 3.15  OK       FAILED   AssertionError: 17.17 != 17.18

# the test that catches each edit
Edit                  Failing test
--------------------  -------------------------------------------------------------------------------
or_default            test_shipping_by_region
truthy_qty            test_lines_with_zero_or_negative_qty_are_skipped
floor_after_shipping  test_a_coupon_bigger_than_the_order_stops_at_zero_and_shipping_is_still_charged
sum_builtin           test_cents_come_from_the_running_total
```

## Why does sum() change the cents on Python 3.12 and later?

Python 3.12 changed how sum() adds floats, so its last bits can differ from a running total. In the mock round one order is exactly halfway between 17.17 and 17.18 in decimal arithmetic: the running total rounds it to 17.18, while sum() gives 17.174999999999997 and rounds it to 17.17.

That order is TIE in the test file: three books at 2.01, one gadget at 1.34 and one food item at 5.14, shipped to the UK, which costs exactly 17.175 in decimal. The Python docs describe the change: "Changed in version 3.12: Summation of floats switched to an algorithm that gives higher accuracy and better commutativity on most builds."

Higher accuracy is not the same as matching the decimal bill. Exact decimal arithmetic rounds 17.175 to 17.18 under both half-even and half-up, so the running total gets the cents right here by the luck of its last bits, and sum() does not.

The textbook case shows the same change: ten additions of 0.1 give 0.9999999999999999 as a running total on every build, and sum() gives 1.0 on 3.12 and later. Real money code should not use binary floats at all, but switching inside a refactor is a behavior change you park, not a cleanup you slip in.

Predict before you open the answer: out of 400,000 random two- and three-line orders, how many get a different cent from sum()? None, tens, hundreds or thousands?

```text
# the sum() edit, run on CPython 3.12.16
$ python3 -m unittest
..F.....
======================================================================
FAIL: test_cents_come_from_the_running_total (test_orders.OrderTotalTests.test_cents_come_from_the_running_total)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/app/test_orders.py", line 48, in test_cents_come_from_the_running_total
    self.assertEqual(order_total(TIE), 17.18)
AssertionError: 17.17 != 17.18

----------------------------------------------------------------------
Ran 8 tests in 0.001s

FAILED (failures=1)

# tie_order.py (probes 1 and 2 of our probes.py)
from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP

# 1. the tie order: exact decimal arithmetic, then the float running total, then sum()
exact = Decimal("2.01") * 3 * Decimal("0.9") + Decimal("1.34") * Decimal("1.2") + Decimal("5.14") + 5
print("tie order, exact decimal total incl. shipping 5:", exact, "| half-even:", exact.quantize(Decimal("0.01"), ROUND_HALF_EVEN), "| half-up:", exact.quantize(Decimal("0.01"), ROUND_HALF_UP))
amounts = [2.01 * 3 * 0.9, 1.34 * 1.2, 5.14]
running = 0
for a in amounts:
    running = running + a
print("tie order, running total + 5 shipping:", repr(running + 5), "->", round(running + 5, 2))
print("tie order, sum() of same   + 5 shipping:", repr(sum(amounts) + 5), "->", round(sum(amounts) + 5, 2))

# 2. the textbook case
loop = 0
for x in [0.1] * 10:
    loop = loop + x
print("ten times 0.1: running total", repr(loop), "| sum()", repr(sum([0.1] * 10)))

$ python3 tie_order.py   # CPython 3.11.2
tie order, exact decimal total incl. shipping 5: 17.175 | half-even: 17.18 | half-up: 17.18
tie order, running total + 5 shipping: 17.175 -> 17.18
tie order, sum() of same   + 5 shipping: 17.175 -> 17.18
ten times 0.1: running total 0.9999999999999999 | sum() 0.9999999999999999

$ python3 tie_order.py   # CPython 3.12.16
tie order, exact decimal total incl. shipping 5: 17.175 | half-even: 17.18 | half-up: 17.18
tie order, running total + 5 shipping: 17.175 -> 17.18
tie order, sum() of same   + 5 shipping: 17.174999999999997 -> 17.17
ten times 0.1: running total 0.9999999999999999 | sum() 1.0
```

### Answer and explanation

836 of 400,000 on CPython 3.12.16, 3.13.15, 3.14.7 and 3.15.2, and none on 3.9.25, 3.10.21 and 3.11.2. A seeded script made up the orders, not real shops, so read the count as rare but real, not as a rate for any store.

Because the effect is rare, a happy-path suite never sees it; the full suite catches the edit only because it includes one hand-picked tie.

```text
# penny_search.py
import random

random.seed(11)
hits = 0
for _ in range(400000):
    amounts = []
    for _ in range(random.randint(2, 3)):
        kind = random.choice(["book", "food", "gadget"])
        price = random.randint(100, 3000) / 100
        qty = random.randint(1, 3)
        amount = price * qty
        if kind == "book":
            if qty >= 3:
                amount = amount * 0.9
        elif kind != "food":
            amount = amount * 1.2
        amounts.append(amount)
    running = 0
    for a in amounts:
        running = running + a
    if round(running, 2) != round(sum(amounts), 2):
        hits = hits + 1
print(hits, "of 400000 random orders differ by a cent")

$ python3 penny_search.py   # CPython 3.12.16
836 of 400000 random orders differ by a cent
$ python3 penny_search.py   # CPython 3.11.2
0 of 400000 random orders differ by a cent
```

## What should you park instead of fixing in a refactoring interview?

Park every bug or doubt you notice: write it down, say it out loud, and fix it in a separate change with its own test. A change that makes the bill look more right is still a behavior change: in the mock round, flooring after shipping turned a bill of 5.0 into 2.0.

The mock round's park list has six items, all visible in the code or the runs. They are questions for the author, not verdicts: pinned means a test records the rule today, not that the rule is right.

The last row is the one no test pins. With member == True, order_total(GADGET, member=2) is 65.0; after the cleanup to if member: it is 62.0, and the full suite stays green on all seven builds. The only protection is an assumption said out loud: I am assuming member is always a bool; is it?

```text
Item                          What the code does today                                 Pinned by a test
----------------------------  -------------------------------------------------------  ----------------
unknown coupon                ignored: NOPE keeps the full price of 65.0               yes
quantity 0 or less            the line is skipped without a message                    yes
unknown region                pays 9: region US costs 5.0 + 9 = 14.0                   yes
coupon bigger than the order  the total stops at 0 and shipping is still charged: 5.0  yes
float money                   ten additions of 0.1 give 0.9999999999999999             one tie case
member == True                member=2 or member='yes' gets no discount                no

# order_total(GADGET, member=value): s5 uses member == True, the cleanup uses if member:
member value  member == True  if member:
------------  --------------  ----------
True          62.0            62.0
1             62.0            62.0
2             65.0            62.0
'yes'         65.0            62.0
```

## How do the same traps look in JavaScript?

JavaScript has the same traps in different places: || treats a legitimate 0 as missing, an empty array is truthy where Python's is falsy, and toFixed rounds 0.125 up to 0.13 where Python's round() gives 0.12. The probes below print each one, and all three Node.js builds printed the same eleven lines.

The expression SHIPPING['IE'] || 9 is 9 and SHIPPING['IE'] ?? 9 is 0, the JavaScript form of the or default. Our post on choosing between || and ?? follows a zero setting through both operators.

Python's docs say round() sends an exact tie to the even digit, which is why 0.125 gives 0.12; the 0.13 is what these Node.js builds printed.

A reduce is the same running total as a loop, so the tie order gives 17.175 either way and the sum() trap has no twin in these builds. The last line shows that none of the three defines Math.sumPrecise.

```text
# Python, two lines of probes.py
print("round(0.125, 2) =", round(0.125, 2), "| round(0.375, 2) =", round(0.375, 2), "| round(2.675, 2) =", round(2.675, 2))
print("bool([]) =", bool([]), "| bool('0') =", bool("0"))

$ python3 py_side.py
round(0.125, 2) = 0.12 | round(0.375, 2) = 0.38 | round(2.675, 2) = 2.67
bool([]) = False | bool('0') = True

// JavaScript, js_probes.js
const SHIPPING = { IE: 0, UK: 5 };
console.log("SHIPPING['IE'] || 9  ->", SHIPPING["IE"] || 9);
console.log("SHIPPING['IE'] ?? 9  ->", SHIPPING["IE"] ?? 9);
console.log("SHIPPING['US'] ?? 9  ->", SHIPPING["US"] ?? 9);
console.log("Boolean([])          ->", Boolean([]));
console.log("Boolean('0')         ->", Boolean("0"));
console.log("(0.125).toFixed(2)   ->", (0.125).toFixed(2));
console.log("Math.round(0.125 * 100) / 100 ->", Math.round(0.125 * 100) / 100);

const amounts = [2.01 * 3 * 0.9, 1.34 * 1.2, 5.14];
let running = 0;
for (const a of amounts) running = running + a;
console.log("tie order running total + 5 ->", running + 5, "toFixed(2) ->", (running + 5).toFixed(2));
console.log("tie order reduce        + 5 ->", amounts.reduce((x, y) => x + y, 0) + 5);
console.log("[0.1 x 10] reduce       ->", Array(10).fill(0.1).reduce((x, y) => x + y, 0));
console.log("typeof Math.sumPrecise  ->", typeof Math.sumPrecise);

$ node js_probes.js
SHIPPING['IE'] || 9  -> 9
SHIPPING['IE'] ?? 9  -> 0
SHIPPING['US'] ?? 9  -> 9
Boolean([])          -> true
Boolean('0')         -> true
(0.125).toFixed(2)   -> 0.13
Math.round(0.125 * 100) / 100 -> 0.13
tie order running total + 5 -> 17.175 toFixed(2) -> 17.18
tie order reduce        + 5 -> 17.175
[0.1 x 10] reduce       -> 0.9999999999999999
typeof Math.sumPrecise  -> undefined
```

## What should you say out loud in a refactoring interview?

Say what must stay the same, what is pinned, what you changed, what you parked and what comes next, one short sentence each. Saying the expected result before each rerun turns the run into a test of your change, and a surprise tells you which assumption to drop.

These lines are our suggestion, not a script any round expects. If you are stuck, say what you have ruled out and what the next rerun would show.

```text
Say      Example from the mock round (our suggestion)
-------  -----------------------------------------------------------------------------------------
Same     "Everything order_total returns must stay the same, to the cent."
Pinned   "Eight tests pass today; they pin zero quantities, the floor, shipping and one tie."
Changed  "One change: the shipping chain is now SHIPPING.get(region, DEFAULT_SHIPPING)."
Parked   "Unknown regions pay 9, and member == True gives member=2 no discount. Parking both."
Next     "All eight pass. Next I'd name the member check, if you confirm member is always a bool."
```

## How do you practice refactoring interview questions?

Practice on messy code you did not write, with the AI and autocomplete off: pin it with tests, refactor in small steps, rerun everything after each one, and write down what you parked. Then score yourself with the five-point list below and repeat the step you skipped. The plan and the list are our suggestion, not a tested method.

If you have no messy code to hand, take one of your own old functions, or swap code and tests with a colleague, and set a goal such as making a new rule a one-line change. A goal gives you an honest place to stop.

Log what you parked, as in the park table above, and begin the next sitting with the kind of trap you missed.

```text
30-minute refactoring interview practice plan (our suggestion; planned minutes, not measured)
Minutes  Step
-------  -------------------------------------------------------------------------------------
3        Scope: read the code and write what must not change, plus one question for the author
5        Pin: run the tests, then add one test for each odd branch you plan to touch
14       Step: four to six small changes, rerunning every test after each one
3        Park: one line per bug or doubt, said out loud
5        Stop: a three-line summary, then score yourself with the rubric below

Five-point rubric for each practice round (our suggestion)
Point    You earn it when you...
-------  ---------------------------------------------------------------------------------
1 Scope  wrote down what must not change before you edited anything
2 Pin    ran the tests before the first edit and added one for each odd branch you touched
3 Step   made one change per run and reran every test each time
4 Park   wrote down each bug you noticed instead of fixing it inside the refactor
5 Stop   stopped on a green suite and said what changed and what you parked
```

## Can you use ChatGPT or another AI in a refactoring interview?

It depends on the round, so ask in advance and follow the rules you are given: some formats may allow an assistant and others may not. Practice with the AI off either way, because the hard part is judging a change, and a suggested refactor is only a diff to check with the same pinned tests.

The mock round shows why: each of the four traps is a small edit that reads like a cleanup, and all four pass the happy-path tests. Whoever writes a change, you or a tool, it is done when the full suite passes on the runtime you ship on, not when it reads well.

Review any suggested change as a diff: ask what behavior it touches, run the probe that would show it, and rerun everything. Our post on reading a code diff for behavior covers that habit, and our code review interview post practices it on four diffs.

## Refactoring interview questions: five quick answers

What do refactoring interview questions look like? Formats vary, so ask: a prompt may give you working code, with or without tests, and a goal such as making it easier to change. In our mock round it is a 27-line function and three happy-path tests, and you stop on a green suite and a short summary.

Should you fix the bugs you find while refactoring? No: park them, say them out loud, and fix them in a separate change with their own test. In the mock round, an edit that looked like a bug fix turned a bill of 5.0 into 2.0, and only a pinned test caught it.

How do you know a refactor did not change behavior? Only your tests tell you, and only about what they pin, so rerun all of them after every change and on every runtime you support. In the mock round the sum() edit passed on CPython 3.11.2 and failed on 3.12.16 with the same eight tests.

Is a refactoring interview the same as a code review interview? No. A code review interview centers on a diff you judge, while a refactoring round asks you to produce a change to structure only, with behavior untouched; the habits overlap, and our code review interview post has four diffs to practice on.

Will practicing this routine get you through a refactoring round? We cannot promise any interview result, and formats differ, so ask what your own round includes. The routine trains one habit, pinning behavior before changing structure, which helps in any format; our page on preparing for a coding interview without an assistant covers the wider week.

## References and next steps

[Martin Fowler: Definition of Refactoring](https://martinfowler.com/bliki/DefinitionOfRefactoring.html)
[Michael Feathers: Characterization Testing](https://michaelfeathers.silvrback.com/characterization-testing)
[Python documentation: built-in functions, sum() and round()](https://docs.python.org/3/library/functions.html#sum)
[Unrust blog: Debugging interview: 6 steps and a mock round](https://unrust.dev/blog/debugging-interview)
[Unrust blog: Code review interview: a rubric and 4 diffs](https://unrust.dev/blog/code-review-interview)
[Unrust blog: Read a code diff for behavior, not just changed lines](https://unrust.dev/blog/review-a-code-diff-with-intent)
[Unrust blog: Keep zero: choosing between || and ?? in JavaScript](https://unrust.dev/blog/javascript-defaults-or-vs-nullish)
[Unrust use case: How to Prepare for a Coding Interview Without an Assistant](https://unrust.dev/use-cases/prepare-for-a-coding-interview)

[How do you review AI-generated code?](https://unrust.dev/guides/reviewing-ai-generated-code/index.md)

## See how you read code with the AI off

Take Unrust's free diagnostic with AI and autocomplete off: about 14 minutes in one sitting, with no account needed for your first read. Two of its six skills, flaw-finding (reading logic against intent) and idiom (idiomatic versus clumsy code), are the reading skills a refactor leans on. It is a snapshot of unassisted reasoning on short exercises and cannot predict interview success.

[Take the free diagnostic](https://unrust.dev/diagnostic/index.md)
