Refactoring in Small Steps

Topics Covered

Why Small Steps Win

The cost of a big change

The benefit of small steps

What counts as small

Small steps are faster

How interviewers see it

An example in Python

An example in TypeScript

An example in Java

Summary

Small steps outside the twist

Small steps and the regression net

A characterisation test in Python

Common objections

What to take from this section

Small steps at every level

Once you know what a twist requires and have decided to reshape rather than patch, you have to make the change. The way you make it matters as much as the result. A large change made in one go, by you or by the assistant, is hard to review, hard to debug and hard to recover from. The same change made as a sequence of small steps, each checked before the next, is easy on all three counts. This lesson covers how to refactor in small steps during an interview, with and without the assistant.

One big change makes failures impossible to untangle.

The cost of a big change

When you make many edits at once and run the tests, one of two things happens. Either everything passes, and you have learned little about which edits mattered, or several tests fail, and you must work out which edit caused which failure. The second is common, and it is expensive: every failure has several possible causes, the causes interact and the debugging can take longer than the change itself. In a sixty minute round, a big change that goes wrong can consume the rest of the time.

Assistant generated big changes are worse, because you did not write them. You have to read a long diff, understand it and then debug it, all at once. The temptation to accept it without reading is strong, and so is the risk.

The benefit of small steps

A small step changes one thing. If the tests stay green, you know that step is safe. If they go red, you know exactly what caused it: the one thing you just changed. Debugging is reduced to reading a few lines. And if a step turns out to be wrong, undoing it costs nothing, because you only lose a minute of work.

Small steps also keep you in a working state. At every point, the code runs and the tests pass. If time runs out, you can stop at the last green step and describe what remains, instead of being left with a broken half change.

What counts as small

A step is small if you can describe it in one short sentence and check it in one test run. Rename this function. Extract the position calculation into a helper. Change the map's key from product id to line id. Add the new branch for heavy items. Each of these is a few lines. A step like implement the twist is not small; it is a whole sequence of steps.

As a rough guide, a step should change fewer than twenty lines and take less than two minutes. If a step is going to be larger, look for a way to split it.

Small steps are faster

It can feel slower to make five small changes than one large one. In practice it is usually faster, because almost no time goes into debugging. A large change that works first time is quicker, but in an interview, under pressure, with code you did not write, that is not the common case. Candidates who work in small steps typically finish the twist sooner and with fewer surprises.

How interviewers see it

Interviewers notice how a candidate changes code. A candidate who makes one large edit, runs the tests, sees five failures and starts guessing looks out of control. A candidate who says I will do this in three steps, and then runs the tests after each, looks like an engineer who changes production code safely. The second impression is a strong signal at every level, and especially at senior levels, where changing shared code without breaking it is part of the job.

An example in Python

The twist: order lines can now repeat a product, so a map keyed by product id must be keyed by line id.

Big change: rewrite the reservation, invoice and stock functions to use line ids, all at once.

Small steps:

  1. Add a line id field to each order line, unused. Run tests: green.
  2. Change the reservation map to use line id. Run tests: green.
  3. Change the invoice grouping to use line id. Run tests: one red, the invoice test that expected merged lines. Update it, with a note. Green.
  4. Change the stock check. Run tests: green.
  5. Add the new test with repeated products. Green.

Five steps, each checked, each described in a sentence.

An example in TypeScript

typescript
1// step 1: extract, no behaviour change
2function eventKey(e: Ev): [number, string] {
3  return [e.start, ""];
4}
5// step 2: use eventKey in the sort, still green
6// step 3: change eventKey to include the lower case title, the new tie rule

The first two steps reshape the code without changing behaviour. The third is a one line behaviour change in a place that is now easy to find.

An example in Java

In Java, an IDE's automated refactorings, such as rename, extract method and change signature, are the safest small steps available, because the tool updates every caller. Use them when you can. They turn steps that would be error prone by hand into steps that are almost always correct.

Summary

Big changes make failures hard to trace and hard to undo. Small steps change one thing, keep the code working and make every failure obvious. They are usually faster, and they look like the way production code should be changed.

Small steps outside the twist

Small steps are not only for the twist. They help any time you change code that already works: fixing a bug found in review, improving performance, adapting assistant code to fit the codebase's style. In each case, the same rule applies. Change one thing, run the tests, keep the green state and move on. The twist is simply where the habit pays off most, because it is where the largest changes to working code happen.

Small steps and the regression net

Small steps depend on the tests, and they also make the tests more valuable. A test that goes red right after a ten line change points at those ten lines. The same test going red after a two hundred line change points at nothing in particular. The suite you built earlier in the round, with a test for each bug and each clause, is what makes small steps safe. Without it, a green run after a step means much less.

If the area you are about to refactor has no tests, add one or two characterisation tests first. A characterisation test records what the code does now, right or wrong, so that a refactor which changes it shows up at once. Write them quickly, from a few representative inputs and the current outputs, and mark them clearly so nobody mistakes them for statements of the rule.

A characterisation test in Python

python
1def test_characterise_fee_before_refactor():
2    # records current behaviour, not the rule
3    assert shipping_fee(order(total=20, items=["a", "b"])) == 7
4    assert shipping_fee(order(total=60, items=["a"])) == 6

Two lines of assertions, written in a minute. Every refactoring step after this must leave them green.

Common objections

Some candidates feel that small steps look slow or timid. Interviewers rarely see it that way. A steady sequence of green steps reads as competence. The candidate who makes a large change quickly and then spends ten minutes debugging is the one who looks slow. If you are worried about pace, narrate the steps briefly so the interviewer can see the progress.

What to take from this section

Small steps make failures easy to trace and easy to undo, keep the code working at every point and look like professional practice. They depend on tests, so add characterisation tests where none exist before you start.

Small steps at every level

Junior candidates benefit from small steps because they reduce debugging, and senior candidates because they show control. Either way, the habit is the same, and it is worth practising until it is the default way you change code.

One sentence, one test run

A step is small if you can describe it in one short sentence and check it with one test run. If you cannot, split it.