Skip to content

Extract function: give a fragment a name

The most used refactoring: turn a block of code that does one thing into a function named after what it does, step by step and without changing behaviour.

4 min readRefactoring

Extract function takes a fragment that you have to read to understand —usually one with a comment on top— and moves it into its own function whose name says what it does. The original code calls the new function. Nothing changes for the program; everything changes for the next person who reads it.

The problem

A situation where the obvious design starts to hurt.

The monthly invoice of a coworking space is computed in one function that first adds up a member's booked hours in a loop and then works out the hourly rate for extra hours, including a discount for founding members. Both blocks carry a comment explaining what they do, and the hourly-rate rule is copied, slightly differently, in the function that shows a quote on the website.

To understand the invoice you have to read the loop; to change the discount you have to find both copies.

Before and after

The same code, before and after the change.

Before

function invoiceFor(member: Member, bookings: Booking[], month: string): Invoice {
  // hours booked this month
  let hours = 0;
  for (const b of bookings) {
    if (b.memberId === member.id && b.start.startsWith(month)) {
      hours += (Date.parse(b.end) - Date.parse(b.start)) / 3_600_000;
    }
  }
  const extra = Math.max(0, hours - PLANS[member.plan].includedHours);
  // founding members keep a 10 % discount on extra hours
  let rate = PLANS[member.plan].hourlyRate;
  if (member.joinedAt < "2023-01-01") rate = rate * 0.9;
  const net = PLANS[member.plan].monthlyFee + extra * rate;
  return { memberId: member.id, month, net: round2(net), total: round2(net * 1.21) };
}

After

function invoiceFor(member: Member, bookings: Booking[], month: string): Invoice {
  const plan = PLANS[member.plan];
  const extra = Math.max(0, hoursBooked(member.id, bookings, month) - plan.includedHours);
  const net = plan.monthlyFee + extra * overageRate(member);
  return { memberId: member.id, month, net: round2(net), total: round2(net * 1.21) };
}

function hoursBooked(memberId: string, bookings: Booking[], month: string): number {
  let hours = 0;
  for (const b of bookings) {
    if (b.memberId === memberId && b.start.startsWith(month)) {
      hours += (Date.parse(b.end) - Date.parse(b.start)) / 3_600_000;
    }
  }
  return hours;
}

/** Founding members (joined before 2023) keep a 10 % discount on extra hours. */
function overageRate(member: Member): number {
  const rate = PLANS[member.plan].hourlyRate;
  return member.joinedAt < "2023-01-01" ? rate * 0.9 : rate;
}

Why it's worth it

What the change buys you.

The comment above a block is a name waiting to happen. Once the block is a function, invoiceFor reads in four lines as the rule it is —allowance, extra hours, rate, VAT— and each detail lives in one place you can test on its own.

The extracted overageRate can now be reused by the quote on the website, so the discount stops existing in two versions. The name and the docstring carry the business reason that was hidden in a comment.

  • Code reads at one level of detail: the caller shows the what, the extracted functions the how.
  • Each extracted rule can be tested and reused without the rest.
  • Names replace comments, and unlike comments they can't drift away from the code.

Careful with

  • If a fragment assigns several variables that are used afterwards, extract smaller pieces or group the values first; a function returning five things is not an improvement.
  • Don't extract a function whose name says nothing more than its body (addOne); inline function is the opposite move for exactly that case.
  • In code without tests, prefer your editor's automated «Extract function» over doing it by hand.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests cover the function; if they don't, write one that pins down today's output for a couple of realistic members.

  2. Pick a fragment that does one thing and name it after what it returns or does, not how: hoursBooked, not loopBookings.

  3. Create the new function and copy the fragment into it, leaving the original in place for now.

  4. Look at the variables the fragment uses: those it only reads become parameters; one it assigns and is used afterwards becomes the return value.

  5. Replace the original fragment with a call to the new function and run the tests.

  6. Delete the comment that the name now makes redundant, and look for other copies of the same fragment to replace with the call.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

How small should the extracted function be?

As small as it needs to be to have one clear name. A two-line function with a good name is fine; a twenty-line one is fine too if it does one thing.

Should the extracted function be private?

Start private or module-local. Make it public only when someone else needs it, as the website quote does with overageRate here.

What's the difference with extract method?

None in practice: «method» when it ends up in a class, «function» when it doesn't. The steps are the same.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide2 of 7 · Techniques: composing functionsInline Function: Remove Indirection That Adds NothingRead the next one