Skip to content

Long method: when one function does the whole job

How to spot a function that has grown too long, why it happens, and the refactorings that split it into pieces you can read and test.

5 min readCode smellBloat

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;
}

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.

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.

Next guide2 of 5 · Smells: bloatLarge ClassRead the next one