Long Method

November 24, 202611 minutes

A method you have to scroll through hides where everything is. Learn to spot Long Method and break it into small methods with good names: name the intent.

A bug report comes in: overtime pay is wrong. You open the payroll code and find the method that prints a payslip. It’s two hundred lines long. You scroll, and scroll, and scroll some more, looking for the one part about overtime. It’s in there somewhere, between the tax rules and the printing. This code smell is called Long Method.

Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.

The method you have to scroll

A long method feels like a book with no chapters and no table of contents. To find one thing, you have to read everything. In this lesson we’ll see what a long method looks like, why it hurts, how to spot it, and how to break it into pieces with good names.

What it looks like

Here’s a short version of that method. printPayslip takes an employee and does everything itself:

void printPayslip(Employee e) {
    // calculate gross pay
    double gross = e.getHourlyRate() * Math.min(e.getHours(), 40);
    if (e.getHours() > 40) {
        gross += (e.getHours() - 40) * e.getHourlyRate() * 1.5;
    }
    // calculate tax
    double tax;
    if (gross > 1000) {
        tax = gross * 0.3;
    } else {
        tax = gross * 0.2;
    }
    // deductions
    double pension = gross * 0.05;
    double net = gross - tax - pension;
    // print the payslip
    System.out.println("Payslip for " + e.getName());
    System.out.println("Gross:   " + gross);
    System.out.println("Tax:     " + tax);
    System.out.println("Pension: " + pension);
    System.out.println("Net:     " + net);
}

First it works out the gross pay, with overtime. Then the tax. Then the pension deduction and the net pay. And finally, it prints the payslip.

The printPayslip method contains four jobs, in order: calculate gross pay with overtime, calculate tax, deductions for pension and net pay, and printing the payslip. The printPayslip method contains four jobs, in order: calculate gross pay with overtime, calculate tax, deductions for pension and net pay, and printing the payslip.
One method, four jobs.

Notice the comments: calculate gross pay, calculate tax, deductions, print. They’re chapter titles, scribbled in the margin. And notice the temporary variables: gross, tax, pension and net. Each one lives for the whole method, and every section can touch it. So before you change one line, you have to check every line below it.

Martin Fowler calls this smell Long Method in Refactoring: a method that has grown to do too much. Here, one method has four jobs, and each job is marked by a comment instead of a name.

Real long methods share a few shapes:

  • You have to scroll. The method doesn’t fit on one screen.
  • Comment headers split it into sections.
  • Many temporary variables live from the top to the bottom.
  • Deep nesting pushes the code to the right.

Why it hurts

It’s hard to understand. To read the last line, you have to keep every variable in your head. Where was gross set? Was it changed since? Is tax already final?

It’s hard to change. To fix the overtime rule, you first have to find it, and make sure nothing below depends on the old value. Everything after the overtime lines reads gross.

You can’t reuse any of it. HR wants net pay on a dashboard. There’s no method to call, so somebody copies the lines:

// DashboardService: copied from printPayslip
double gross = e.getHourlyRate() * Math.min(e.getHours(), 40);
if (e.getHours() > 40) {
    gross += (e.getHours() - 40) * e.getHourlyRate() * 1.5;
}
double tax = gross > 1000 ? gross * 0.3 : gross * 0.2;
double net = gross - tax - gross * 0.05;

Now the tax rule lives in two places, and the next change to it will be made in only one of them:

The tax rule exists twice, once inside printPayslip and once copied into DashboardService. A change to the tax rate updates printPayslip, while the dashboard keeps the old rate. The tax rule exists twice, once inside printPayslip and once copied into DashboardService. A change to the tax rate updates printPayslip, while the dashboard keeps the old rate.
What can't be called gets copied, and copies drift apart.

It’s hard to test. The only thing this method produces is printed text. To test the tax rule, you’d have to read it back from the console.

What can’t be named can’t be reused or tested.

How to spot it

How do you spot a long method? Look for five signals.

  1. You scroll. If a method doesn’t fit on your screen, you can’t see what it does all at once.
  2. Comment headers. A comment that announces a section is a method name waiting to happen. (Fowler’s advice: whenever you feel the need to write a comment, write a method instead.)
  3. Many temps. Lots of temporary variables that live from the top of the method to the bottom.
  4. Deep nesting. When the code drifts to the right in the shape of an arrow, each level is another thing to keep in your head.
  5. Hard to name. If an honest name needs the word and, like calculateAndTaxAndPrint(), the method is doing more than one thing.

Notice that none of these signals is a line count. The real test is the distance between what a method does and how it does it. A ten-line method can be too long if it mixes three levels of detail; a twenty-line method can be fine if every line is at the same level.

The key insight: name the intent

So what’s the fix? The most important refactoring of all: Extract Method.

Take one section, move it into its own method, and name that method after what it does, not how it does it. The comment calculate gross pay becomes a method called grossPay. The comment was trying to be a name all along. Do the same for the tax, the pension, and the printing.

Each comment header in printPayslip becomes the name of an extracted method: calculate gross pay becomes grossPay, calculate tax becomes tax, deductions becomes pension, and print the payslip becomes printLines. Each comment header in printPayslip becomes the name of an extracted method: calculate gross pay becomes grossPay, calculate tax becomes tax, deductions becomes pension, and print the payslip becomes printLines.
A comment header is a method name waiting to happen.

Now look at printPayslip. Four lines. It reads like a table of contents: gross pay, tax, pension, print.

void printPayslip(Employee e) {
    double gross = grossPay(e);
    double tax = tax(gross);
    double pension = pension(gross);
    printLines(e, gross, tax, pension);
}

The details didn’t disappear. They moved into small methods, each with one job:

double grossPay(Employee e) {
    double gross = e.getHourlyRate() * Math.min(e.getHours(), 40);
    if (e.getHours() > 40) {
        gross += (e.getHours() - 40) * e.getHourlyRate() * 1.5;
    }
    return gross;
}

double tax(double gross) {
    return gross > 1000 ? gross * 0.3 : gross * 0.2;
}

(pension(gross) returns gross * 0.05, and printLines holds the five println calls.)

Sequence: printPayslip calls grossPay and gets the gross amount, calls tax with gross and gets the tax, calls its own pension method, then calls printLines with the employee and all three values. Sequence: printPayslip calls grossPay and gets the gross amount, calls tax with gross and gets the tax, calls its own pension method, then calls printLines with the employee and all three values.
The top-level method only coordinates; each step has a name.

And the overtime bug now has an address: it lives in grossPay. You can read it, test it on its own, and fix it without touching the printing.

Name the intent. Small methods read like a table of contents.

A practical note: IDEs automate this (IntelliJ and Eclipse: Refactor → Extract Method), and they work out the parameters and return value for you. If the tool asks for many parameters, that’s a hint that temps are in the way, which brings us to the next step. (You may also notice that grossPay only talks to Employee. That’s a hint it might later move there, see Feature Envy.)

Temps in the way: Replace Temp with Query and Introduce Parameter Object

There’s one thing left that bothers us: printLines takes four parameters. The temporary variables are still being passed around.

Two refactorings help:

  • Replace Temp with Query turns a variable into a method you call when you need it. The pension and the net pay become small queries, pension() and net().
  • Introduce Parameter Object groups values that always travel together into one object. It’s like stapling four loose pages into a booklet. Here, that booklet is a Payslip record:
record Payslip(double gross, double tax) {
    double pension() { return gross * 0.05; }
    double net()     { return gross - tax - pension(); }
}

Now printPayslip passes one payslip:

void printPayslip(Employee e) {
    double gross = grossPay(e);
    Payslip slip = new Payslip(gross, tax(gross));
    print(e.getName(), slip);
}
Class diagram: the Payslip record holds gross and tax and offers pension() and net(). PayrollService creates Payslips, and DashboardService reads net() from a Payslip instead of copying the calculation. Class diagram: the Payslip record holds gross and tax and offers pension() and net(). PayrollService creates Payslips, and DashboardService reads net() from a Payslip instead of copying the calculation.

And remember the dashboard? It doesn’t copy anything anymore. It just asks the payslip for its net pay, slip.net(). Fewer temps, shorter parameter lists, and logic you can reuse.

A second example: the parking fee

Here’s a second example, from a parking garage. This method works out the fee when you drive out. The first few minutes are free. At night, there’s a flat rate. Otherwise, you pay by the hour, and less if your ticket was validated:

double fee(Ticket t, LocalDateTime exit) {
    long minutes = Duration.between(t.entry(), exit).toMinutes();
    if (minutes > 15) {
        if (exit.getHour() >= 22 || exit.getHour() < 6) {
            return 8.0;
        } else {
            if (t.isValidated()) {
                return Math.ceil(minutes / 60.0) * 1.5;
            } else {
                return Math.ceil(minutes / 60.0) * 3.0;
            }
        }
    }
    return 0;
}

See how the code drifts to the right? Every condition is another level of nesting, and you have to work out what each condition means. The rules themselves are simple:

Decision flowchart for the parking fee: if the stay is within the 15-minute grace period, the fee is zero. Otherwise, if the exit is at night, between 10pm and 6am, it is a flat rate. Otherwise the fee is the hours started times the hourly rate, which is lower for a validated ticket. Decision flowchart for the parking fee: if the stay is within the 15-minute grace period, the fee is zero. Otherwise, if the exit is at night, between 10pm and 6am, it is a flat rate. Otherwise the fee is the hours started times the hourly rate, which is lower for a validated ticket.
The rules are simple; the nesting hides them.

The refactoring is called Decompose Conditional: extract each condition into a method whose name says what it means, isGracePeriod, isNight, hourlyRate. Then return early with guard clauses (Fowler’s Replace Nested Conditional with Guard Clauses), so the main path stays flat:

double fee(Ticket t, LocalDateTime exit) {
    long minutes = Duration.between(t.entry(), exit).toMinutes();
    if (isGracePeriod(minutes)) return 0;
    if (isNight(exit)) return NIGHT_FLAT_RATE;
    return hoursStarted(minutes) * hourlyRate(t);
}

boolean isNight(LocalDateTime time) {
    return time.getHour() >= 22 || time.getHour() < 6;
}

double hourlyRate(Ticket t) {
    return t.isValidated() ? 1.5 : 3.0;
}

(isGracePeriod is minutes <= 15, hoursStarted is (long) Math.ceil(minutes / 60.0), and NIGHT_FLAT_RATE is 8.0.) Now the method reads almost like the sign at the garage entrance: grace period, free. Night, flat rate. Otherwise, hours times the rate.

Name the condition, not just the block.

When the temps are tangled: Replace Method with Method Object

Sometimes the local variables are so tangled that every extraction needs five parameters. Then there’s a bigger move: Replace Method with Method Object. Turn the whole method into its own class. The local variables become fields:

class PayslipPrinter {
    private final Employee e;
    private double gross, tax, pension;

    PayslipPrinter(Employee e) { this.e = e; }

    void print() {
        computeGross();
        computeTax();
        computePension();
        printLines();
    }
}

Now every step can read and write those fields directly, so you can extract freely, with no parameters at all. The caller creates a payslip printer and calls print: new PayslipPrinter(e).print();. When a chapter grows too big, it becomes its own book.

Class diagram of the method object: PayslipPrinter has the fields e, gross, tax and pension, which used to be the locals of printPayslip, plus print, computeGross, computeTax, computePension and printLines, none of which take parameters. Class diagram of the method object: PayslipPrinter has the fields e, gross, tax and pension, which used to be the locals of printPayslip, plus print, computeGross, computeTax, computePension and printLines, none of which take parameters.

Use it as a stepping stone: once the method is an object, Extract Method is easy, and the result is often clearer than the parameter-heavy version.

Commonly confused: Large Class

Long method is often confused with its neighbor, Large Class. They sound alike, but they’re about different things:

  • A long method is one method that does too many steps.
  • A large class is one class that holds too many responsibilities.

They often show up together. After extracting methods, our PayrollService may own payslips, tax rules and printing, all at once. That’s when the next refactoring is Extract Class, the topic of the Large Class lesson.

Top: Long Method, one method with too many steps, fixed with Extract Method. Bottom: Large Class, PayrollService holding payslips, tax rules and printing, fixed with Extract Class into PayrollService, TaxRules and PayslipFormatter. Top: Long Method, one method with too many steps, fixed with Extract Method. Bottom: Large Class, PayrollService holding payslips, tax rules and printing, fixed with Extract Class into PayrollService, TaxRules and PayslipFormatter.
Too many steps (top) versus too many responsibilities (bottom).

And remember, lots of small methods are not a smell by themselves. A class with twenty two-line methods can be perfectly cohesive; the question is whether they all serve one job.

When it’s acceptable

So is every long method a problem? Not always.

A straight sequence that reads clearly can stay long. This method registers web routes. Each line says exactly what it does; splitting it would only scatter it:

void registerRoutes(Router r) {
    r.get("/payslips", payslips::list);
    r.get("/payslips/{id}", payslips::show);
    r.post("/payslips", payslips::create);
    r.get("/employees", employees::list);
    r.get("/employees/{id}", employees::show);
    r.post("/employees", employees::create);
}

It’s like a phone book: long, but nobody gets lost in it. Field-by-field mappings and setup code often have the same shape.

And performance is rarely a good excuse. Modern compilers (the JVM’s JIT among them) inline small, frequently called methods for you. If you think a call is too slow, measure it first. Most of the time the cost is too small to see, and the readable version wins. Keep hand-inlined code for the rare hot path a profiler actually points at, and leave a comment saying why.

Decision flowchart: is a long method a smell? If each line already says what it does at one level of detail, keep it. If you need comments to find your way and the method is not a measured hot path, extract methods. If a profiler shows a real hot path, keep it inline and document why. Decision flowchart: is a long method a smell? If each line already says what it does at one level of detail, keep it. If you need comments to find your way and the method is not a measured hot path, extract methods. If a profiler shows a real hot path, keep it inline and document why.
The test isn't length; it's whether a reader needs a map.

So the real test isn’t length. It’s whether a reader needs comments to find their way.

Recap

A long method does too much. Spot it by scrolling, comment headers, piles of temporary variables, deep nesting, and names with and. Fix it with Extract Method first. Then replace temps with queries, introduce parameter objects, decompose conditionals, and, when it’s tangled, use a method object.

Recap chain: spot the sections by their comment headers; extract each into a method named after its intent; clean up temps and conditions with Replace Temp with Query, Parameter Object and Decompose Conditional; the result is a method that reads like a table of contents. Recap chain: spot the sections by their comment headers; extract each into a method named after its intent; clean up temps and conditions with Replace Temp with Query, Parameter Object and Decompose Conditional; the result is a method that reads like a table of contents.
Give every section a name.
  • Long Method: a method that has grown to do too much.
  • It hurts because you juggle every temp in your head, changes are risky, nothing can be reused (so it gets copied), and the only way to test it is through its side effects.
  • Spot it: you scroll, comment headers, many temps, deep nesting, a name that needs “and”.
  • Fix it: Extract Method (name the intent), Replace Temp with Query, Introduce Parameter Object, Decompose Conditional with guard clauses, Replace Method with Method Object.
  • Don’t confuse it with Large Class: too many steps vs too many responsibilities.
  • Leave it when it’s a flat, obvious sequence, or a measured hot path.

Give every section a name. Small methods read like a table of contents. Name the intent.

Further reading

  • Martin Fowler, Refactoring: Improving the Design of Existing Code (2nd ed.), chapter 3 (“Long Function”) and the Extract Function, Replace Temp with Query, Introduce Parameter Object, Decompose Conditional and Replace Function with Command refactorings (the first edition calls the last one Replace Method with Method Object).
  • Refactoring.Guru: Long Method
  • Related lessons: Large Class, Feature Envy, Shotgun Surgery, Template Method Pattern (a skeleton of named steps).