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) };
}def invoice_for(member: Member, bookings: list[Booking], month: str) -> Invoice:
# hours booked this month
hours = 0.0
for b in bookings:
if b.member_id == member.id and b.start.startswith(month):
hours += (datetime.fromisoformat(b.end) - datetime.fromisoformat(b.start)).total_seconds() / 3600
extra = max(0.0, hours - PLANS[member.plan].included_hours)
# founding members keep a 10 % discount on extra hours
rate = PLANS[member.plan].hourly_rate
if member.joined_at < "2023-01-01":
rate = rate * 0.9
net = PLANS[member.plan].monthly_fee + extra * rate
return Invoice(member.id, month, round(net, 2), round(net * 1.21, 2))<?php
function invoiceFor(Member $member, array $bookings, string $month): Invoice
{
// hours booked this month
$hours = 0.0;
foreach ($bookings as $b) {
if ($b->memberId === $member->id && str_starts_with($b->start, $month)) {
$hours += (strtotime($b->end) - strtotime($b->start)) / 3600;
}
}
$extra = max(0, $hours - PLANS[$member->plan]['includedHours']);
// founding members keep a 10 % discount on extra hours
$rate = PLANS[$member->plan]['hourlyRate'];
if ($member->joinedAt < '2023-01-01') {
$rate = $rate * 0.9;
}
$net = PLANS[$member->plan]['monthlyFee'] + $extra * $rate;
return new Invoice($member->id, $month, round($net, 2), round($net * 1.21, 2));
}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;
}def invoice_for(member: Member, bookings: list[Booking], month: str) -> Invoice:
plan = PLANS[member.plan]
extra = max(0.0, hours_booked(member.id, bookings, month) - plan.included_hours)
net = plan.monthly_fee + extra * overage_rate(member)
return Invoice(member.id, month, round(net, 2), round(net * 1.21, 2))
def hours_booked(member_id: str, bookings: list[Booking], month: str) -> float:
hours = 0.0
for b in bookings:
if b.member_id == member_id and b.start.startswith(month):
hours += (datetime.fromisoformat(b.end) - datetime.fromisoformat(b.start)).total_seconds() / 3600
return hours
def overage_rate(member: Member) -> float:
"""Founding members (joined before 2023) keep a 10 % discount on extra hours."""
rate = PLANS[member.plan].hourly_rate
return rate * 0.9 if member.joined_at < "2023-01-01" else rate<?php
function invoiceFor(Member $member, array $bookings, string $month): Invoice
{
$plan = PLANS[$member->plan];
$extra = max(0, hoursBooked($member->id, $bookings, $month) - $plan['includedHours']);
$net = $plan['monthlyFee'] + $extra * overageRate($member);
return new Invoice($member->id, $month, round($net, 2), round($net * 1.21, 2));
}
function hoursBooked(string $memberId, array $bookings, string $month): float
{
$hours = 0.0;
foreach ($bookings as $b) {
if ($b->memberId === $memberId && str_starts_with($b->start, $month)) {
$hours += (strtotime($b->end) - strtotime($b->start)) / 3600;
}
}
return $hours;
}
/** Founding members (joined before 2023) keep a 10 % discount on extra hours. */
function overageRate(Member $member): float
{
$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.
Make sure tests cover the function; if they don't, write one that pins down today's output for a couple of realistic members.
Pick a fragment that does one thing and name it after what it returns or does, not how:
hoursBooked, notloopBookings.Create the new function and copy the fragment into it, leaving the original in place for now.
Look at the variables the fragment uses: those it only reads become parameters; one it assigns and is used afterwards becomes the return value.
Replace the original fragment with a call to the new function and run the tests.
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.
- Cart total with a couponSolve the exercise