Skip to the content

Lesson 157 of 296

Refactoring safely

What you will learn

  • What refactoring is, and what it is not
  • Why tests come first
  • Small, safe steps
  • The most useful refactorings
  • A full worked example: from a messy function to clean, tested pieces
On this page

What is refactoring?

Refactoring means changing the structure of code without changing what it does. The goal is code that is easier to read, test and change. Adding features or fixing bugs is not refactoring; do those separately.

Tests first

Before refactoring, make sure tests describe the current behaviour. If there are none, write characterisation tests: run the current code with several inputs and record its outputs as the expected results, even if some look odd. Then any change in behaviour is caught immediately.

Small steps

  1. Make one small change.
  2. Run the tests.
  3. Commit (Part 8).
  4. Repeat.

If a test fails, you know exactly which small change caused it. Large rewrites in one go are where bugs hide.

Useful refactorings

RefactoringWhat it means
RenameGive variables and functions names that explain them
Extract functionMove a block with one job into its own named function
Guard clausesReplace deep nesting with early returns (Lesson 36)
Replace magic numbersconst VAT_RATE = 0.2 instead of 0.2 in the code
Remove duplicationTwo similar blocks become one function with parameters
Replace conditional with a lookupA long if/else chain becomes an object or Map
Separate calculation from side effectsPure logic in one function; saving, logging, sending in another
Introduce a typeReplace loose objects and strings with clear types or unions

A worked example

A messy function from an old codebase, around 40 lines, that calculates a delivery quote:

function quote(o) {
  var t = 0;
  for (var i = 0; i < o.items.length; i++) {
    t = t + o.items[i].p * o.items[i].q;
  }
  var d = 0;
  if (o.country == "UK") {
    if (t > 5000) { d = 0; } else { if (o.express) { d = 999; } else { d = 399; } }
  } else {
    if (o.country == "IE") {
      if (o.express) { d = 1499; } else { d = 799; }
    } else {
      if (o.express) { d = 2999; } else { d = 1499; }
    }
  }
  var v = Math.round(t * 0.2);
  console.log("quote for " + o.customer + ": " + (t + d + v));
  return { subtotal: t, delivery: d, vat: v, total: t + d + v };
}

Problems: unclear names, var, ==, deep nesting, magic numbers, logging mixed with calculation, no types, and delivery rules hidden in nested ifs.

Step 1: characterisation tests. Record outputs for: UK under and over £50, UK express, Ireland standard and express, another country, and an empty basket.

Step 2 onwards: refactor in small steps, running the tests after each one:

TypeScript
type QuoteItem = { pricePence: number; quantity: number };
type Country = "UK" | "IE" | "OTHER";

type QuoteInput = {
  customer: string;
  country: string;
  express: boolean;
  items: QuoteItem[];
};

type Quote = {
  subtotal: number;
  delivery: number;
  vat: number;
  total: number;
};

const VAT_RATE = 0.2;
const UK_FREE_DELIVERY_OVER_PENCE = 5000;

const DELIVERY_PENCE: Record<Country, { standard: number; express: number }> = {
  UK: { standard: 399, express: 999 },
  IE: { standard: 799, express: 1499 },
  OTHER: { standard: 1499, express: 2999 }
};

function toCountry(code: string): Country {
  return code === "UK" || code === "IE" ? code : "OTHER";
}

function subtotalPence(items: QuoteItem[]): number {
  return items.reduce((sum, item) => sum + item.pricePence * item.quantity, 0);
}

function deliveryPence(country: Country, express: boolean, subtotal: number): number {
  if (country === "UK" && subtotal > UK_FREE_DELIVERY_OVER_PENCE) return 0;
  const rates = DELIVERY_PENCE[country];
  return express ? rates.express : rates.standard;
}

function calculateQuote(input: QuoteInput): Quote {
  const subtotal = subtotalPence(input.items);
  const delivery = deliveryPence(toCountry(input.country), input.express, subtotal);
  const vat = Math.round(subtotal * VAT_RATE);
  return { subtotal, delivery, vat, total: subtotal + delivery + vat };
}

function quoteAndLog(input: QuoteInput, log: (message: string) => void = console.log): Quote {
  const result = calculateQuote(input);
  log(`quote for ${input.customer}: ${result.total}`);
  return result;
}

What changed, and why:

ChangeBenefit
Types for input and outputMistakes caught by the compiler; self-documenting
Clear names (subtotal, pricePence)Easy to read; units are obvious
Constants for VAT and the free delivery thresholdOne place to change; meaning is clear
Delivery rules in a lookup tableAdding a country is one line, not another nested if
Small functions with one job eachEach can be tested alone
calculateQuote is pure; logging is separateEasy to test; no hidden side effects
The logger is injectableTests can check the message without printing

The behaviour is identical: the same characterisation tests pass. Notice one thing kept on purpose: the free delivery rule uses > (over £50), exactly as before. If you think it should be >=, that is a behaviour change: raise it as a question and make it in a separate commit.

When to refactor

  • Before adding a feature to messy code ("make the change easy, then make the easy change").
  • When you touch code and see a small improvement (the "boy scout rule": leave it a bit cleaner than you found it).
  • Not in the middle of an urgent fix, and not without tests.

How to say it in an interview

"Refactoring changes structure without changing behaviour, so first I make sure tests describe the current behaviour, writing characterisation tests if needed. Then I work in small steps, running tests and committing after each: renaming, extracting small functions, adding guard clauses, replacing magic numbers with named constants, replacing nested conditionals with lookup tables, and separating pure calculation from side effects like logging. Anything that would change behaviour I raise as a question and do separately."

Key words

WordMeaning
RefactoringImproving structure without changing behaviour
Characterisation testA test recording what existing code currently does
Extract functionMoving a block of code into its own named function
Magic numberAn unexplained literal number in code
Lookup tableData that replaces a chain of conditions
Side effectA change outside the function, such as logging or saving

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.