A long method isn't about a line count. It's a function that does several things at several levels of detail: it fetches, filters, calculates, formats and sends, with comments acting as section headings. You can't understand any part of it without reading all of it, you can't test the calculation without a mailer, and every change risks breaking a step you weren't looking at.
Signs
How to spot it in a review.
- Comments that work as section titles: «// hours booked this month», «// skip empty invoices».
- You need to scroll to see the whole function, and its name («closeMonth», «process») doesn't tell you what it returns.
- Local variables declared at the top and used fifty lines further down.
- Loops inside loops, and conditions that mix business rules with technical checks.
- Testing one rule means building every argument and mocking every side effect.
- Several people touch it in the same sprint for unrelated reasons.
What it looks like
A typical case, in three languages.
export async function closeMonth(month: string, members: Member[], bookings: Booking[], mailer: Mailer) {
const invoices: Invoice[] = [];
for (const member of members) {
// 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;
}
}
// plan allowance and overage
const included = member.plan === "flex" ? 20 : member.plan === "resident" ? 80 : 0;
const extra = Math.max(0, hours - included);
let rate = member.plan === "flex" ? 9 : 12;
if (member.joinedAt < "2023-01-01") rate = rate * 0.9; // founding members
const base = member.plan === "flex" ? 120 : member.plan === "resident" ? 390 : 0;
const net = Math.round((base + extra * rate) * 100) / 100;
const total = Math.round(net * 1.21 * 100) / 100;
// skip empty invoices
if (total === 0) continue;
const lines = [`Plan ${member.plan}: ${base.toFixed(2)} €`];
if (extra > 0) lines.push(`${extra.toFixed(1)} extra hours × ${rate.toFixed(2)} €`);
lines.push(`VAT 21 %: ${(total - net).toFixed(2)} €`, `Total: ${total.toFixed(2)} €`);
invoices.push({ memberId: member.id, month, net, total });
await mailer.send(member.email, `Your invoice for ${month}`, lines.join("\n"));
}
return invoices;
}async def close_month(month: str, members: list[Member], bookings: list[Booking], mailer: Mailer) -> list[Invoice]:
invoices = []
for member in members:
# 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
# plan allowance and overage
included = 20 if member.plan == "flex" else 80 if member.plan == "resident" else 0
extra = max(0.0, hours - included)
rate = 9 if member.plan == "flex" else 12
if member.joined_at < "2023-01-01":
rate = rate * 0.9 # founding members
base = 120 if member.plan == "flex" else 390 if member.plan == "resident" else 0
net = round(base + extra * rate, 2)
total = round(net * 1.21, 2)
# skip empty invoices
if total == 0:
continue
lines = [f"Plan {member.plan}: {base:.2f} €"]
if extra > 0:
lines.append(f"{extra:.1f} extra hours × {rate:.2f} €")
lines += [f"VAT 21 %: {total - net:.2f} €", f"Total: {total:.2f} €"]
invoices.append(Invoice(member.id, month, net, total))
await mailer.send(member.email, f"Your invoice for {month}", "\n".join(lines))
return invoices<?php
function closeMonth(string $month, array $members, array $bookings, Mailer $mailer): array
{
$invoices = [];
foreach ($members as $member) {
// 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;
}
}
// plan allowance and overage
$included = match ($member->plan) { 'flex' => 20, 'resident' => 80, default => 0 };
$extra = max(0, $hours - $included);
$rate = $member->plan === 'flex' ? 9 : 12;
if ($member->joinedAt < '2023-01-01') {
$rate = $rate * 0.9; // founding members
}
$base = match ($member->plan) { 'flex' => 120, 'resident' => 390, default => 0 };
$net = round($base + $extra * $rate, 2);
$total = round($net * 1.21, 2);
// skip empty invoices
if ($total == 0) {
continue;
}
$lines = [sprintf('Plan %s: %.2f €', $member->plan, $base)];
if ($extra > 0) {
$lines[] = sprintf('%.1f extra hours × %.2f €', $extra, $rate);
}
$lines[] = sprintf('VAT 21 %%: %.2f €', $total - $net);
$lines[] = sprintf('Total: %.2f €', $total);
$invoices[] = new Invoice($member->id, $month, $net, $total);
$mailer->send($member->email, "Your invoice for {$month}", implode("\n", $lines));
}
return $invoices;
}A coworking space closes the month: one function adds up booked hours, applies each plan's allowance and the founding members' discount, works out VAT, formats the email and sends it. The billing rules can't be tested without a mailer, and the plans' numbers are scattered across three conditionals.
Why it happens
How code ends up like this.
- Adding a line where the work happens is always the quickest change. Nobody decides to write a 200-line function; it grows one urgent fix at a time.
- Extracting feels risky without tests, so people add to the function they understand instead of splitting it.
- A single function seems easier to follow «from top to bottom» while it's short, and nobody notices the moment it stops being short.
- Code that mixes calculation and side effects (database, email, HTTP) is hard to split without first separating those two concerns.
Treatment
The refactorings that cure it, and when to choose each.
- Extract function: give a fragment a name
The default cure. Every commented block, every loop body that computes one thing, becomes a function named after what it returns:
hoursBooked,overageRate,invoiceText. - Replace Temp with Query: Turn Local Variables into Methods
A temporary variable holds a value computed at the top and used much later. Turning it into a function makes the blocks independent and easier to extract.
- Introduce Parameter Object: Bundle Parameters That Travel Together
The extracted functions keep needing the same three or four values (month, plan, rates). Group them into one object first.
- Decompose Conditional: Name the Condition and Each Branch
The length comes from a tangled if/else: extract the condition and each branch into functions with business names.
- Replace Function with Command: Turn a Long Function into an Object
The function has so many locals shared between steps that extracting would mean passing ten arguments. Turn it into an object whose fields are those locals.
Payoff
What you get once it's gone.
- Each business rule —allowance, discount, VAT— can be read and tested on its own, without a mailer or a database.
- The top-level function reads like a summary of the process, and the names replace the comments.
- Changes land in small functions with few callers, so reviews are shorter and conflicts rarer.
- Duplicated fragments become visible and can be reused instead of copied.
When to leave it
Sometimes it's not worth fixing.
- A long but flat sequence of steps with no shared state —a migration script, a configuration builder— can be clearer in one place than split across ten tiny functions.
- In hot paths measured with a profiler, an extra call can matter in some runtimes; measure before you inline anything back, it rarely does.
- Code that's about to be deleted or replaced isn't worth polishing; put the effort into the replacement.
Common questions
Short answers to the usual doubts.
How long is too long?
There's no magic number. Ask whether you can say what the function does in one sentence without «and», and whether every line is at the same level of detail. If you're writing comments to separate sections, it's too long.
Don't lots of small functions make the code harder to follow?
Only if they're badly named. A good name lets you skip the body; then you read the top-level function as a summary and dive only into the part you care about.
How do I split it safely without tests?
Write a characterisation test first: call the function with realistic input and assert on what it returns and sends today. Then extract in small steps, running that test after each one.
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