# Long MethodA 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.

{{< lesson-video youtube="st04OZB-aqE" title="Long Method" >}}

## 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:

```java
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.

```mermaid {alt="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." caption="One method, four jobs."}
flowchart TD
  M["printPayslip(e)"] -->|1| G["gross pay<br/>+ overtime"]
  M -->|2| T["tax"]
  M -->|3| D["deductions<br/>pension, net"]
  M -->|4| P["print the<br/>payslip"]
  class M bad
  class G c4
  class T c1
  class D c5
  class P c6
```

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:

```java
// 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:

```mermaid {alt="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." caption="What can't be called gets copied, and copies drift apart."}
flowchart LR
  R["Tax rate<br/>changes"] --> A["printPayslip<br/>updated"]
  R -.-> B["DashboardService<br/>copy: still the old rate"]
  B --> X["Dashboard shows<br/>the wrong net pay"]
  class R hl
  class A good
  class B warn
  class X bad
```

**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.

```mermaid {alt="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." caption="A comment header is a method name waiting to happen."}
flowchart LR
  C1["// calculate gross pay"] --> M1["grossPay(e)"]
  C2["// calculate tax"] --> M2["tax(gross)"]
  C3["// deductions"] --> M3["pension(gross)"]
  C4["// print the payslip"] --> M4["printLines(...)"]
  class C1,C2,C3,C4 muted
  class M1 c4
  class M2 c1
  class M3 c5
  class M4 c6
```

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

```java
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:

```java
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.)

```mermaid {alt="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." caption="The top-level method only coordinates; each step has a name."}
sequenceDiagram
  participant P as printPayslip
  participant G as grossPay
  participant T as tax
  participant L as printLines
  P->>G: grossPay(e)
  G-->>P: gross
  P->>T: tax(gross)
  T-->>P: tax
  P->>P: pension(gross)
  P->>L: printLines(...)
```

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](/code-smells/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:

```java
record Payslip(double gross, double tax) {
    double pension() { return gross * 0.05; }
    double net()     { return gross - tax - pension(); }
}
```

Now `printPayslip` passes one payslip:

```java
void printPayslip(Employee e) {
    double gross = grossPay(e);
    Payslip slip = new Payslip(gross, tax(gross));
    print(e.getName(), slip);
}
```

```mermaid {alt="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."}
classDiagram
  class Payslip {
    <<record>>
    +double gross
    +double tax
    +pension() double
    +net() double
  }
  class PayrollService {
    +printPayslip(Employee e)
    -grossPay(Employee e) double
    -tax(double gross) double
  }
  class DashboardService {
    +showNetPay(Payslip slip)
  }
  PayrollService ..> Payslip : creates
  DashboardService ..> Payslip : asks net()
```

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:

```java
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:

```mermaid {alt="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." caption="The rules are simple; the nesting hides them."}
flowchart TD
  A["Driving out"] --> G{"Within the<br/>grace period?"}
  G -->|yes| Z["free"]
  G -->|no| N{"Night?<br/>10pm to 6am"}
  N -->|yes| F["flat night rate"]
  N -->|no| V{"Ticket<br/>validated?"}
  V -->|yes| L["hours x 1.50"]
  V -->|no| H["hours x 3.00"]
  class G c1
  class N c5
  class V c4
  class Z,F,L,H good
```

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:

```java
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:

```java
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.

```mermaid {alt="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."}
classDiagram
  class PayslipPrinter {
    -Employee e
    -double gross
    -double tax
    -double pension
    +PayslipPrinter(Employee e)
    +print()
    -computeGross()
    -computeTax()
    -computePension()
    -printLines()
  }
  note for PayslipPrinter "former locals are now fields"
```

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](/code-smells/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](/code-smells/large-class/).

```mermaid {alt="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." caption="Too many steps (top) versus too many responsibilities (bottom)."}
flowchart TB
  subgraph LM["Long Method"]
    direction LR
    A["printPayslip()<br/>too many steps"] -->|Extract Method| B["four small<br/>named methods"]
  end
  subgraph LC["Large Class"]
    direction LR
    P["PayrollService<br/>payslips, tax rules,<br/>printing"] -->|Extract Class| T["TaxRules"]
    P -->|Extract Class| F["PayslipFormatter"]
  end
  LM ~~~ LC
  class A bad
  class B good
  class P c5
  class T c1
  class F c6
```

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:

```java
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.

```mermaid {alt="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." caption="The test isn't length; it's whether a reader needs a map."}
flowchart TD
  Q{"Do you need comments<br/>to find your way?"} -->|no, flat and obvious| K["Keep it<br/>(route table, mapping)"]
  Q -->|yes| H{"Profiler shows<br/>a real hot path?"}
  H -->|no| E["Extract Method:<br/>name the intent"]
  H -->|yes, measured| I["Keep it inline,<br/>comment why"]
  class Q,H warn
  class K,I good
  class E hl
```

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.

```mermaid {alt="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." caption="Give every section a name."}
flowchart LR
  A["Spot the sections<br/>comment headers,<br/>temps, nesting"] --> B["Extract Method<br/>name the intent"]
  B --> C["Clean up temps<br/>and conditions"]
  C --> D["Reads like a<br/>table of contents"]
  class A bad
  class B,C hl
  class D good
```

- **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](/code-smells/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](https://refactoring.guru/smells/long-method)
- Related lessons: [Large Class](/code-smells/large-class/),
  [Feature Envy](/code-smells/feature-envy/),
  [Shotgun Surgery](/code-smells/shotgun-surgery/),
  [Template Method Pattern](/patterns/template-method-pattern/) (a skeleton of named steps).
