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.
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.
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.
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:
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:
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 do you spot a long method? Look for five signals.
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.
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.
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.)
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.)
There’s one thing left that bothers us: printLines takes four parameters. The temporary
variables are still being passed around.
Two refactorings help:
pension() and net().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);
}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.
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:
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.
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.
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.
Long method is often confused with its neighbor, Large Class. They sound alike, but they’re about different things:
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.
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.
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.
So the real test isn’t length. It’s whether a reader needs comments to find their way.
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.
Give every section a name. Small methods read like a table of contents. Name the intent.