# Long Parameter ListEight arguments, two of them swapped, and the compiler was happy. Learn to ask four questions of every parameter and shrink a long signature from eight to two.

Maria Garcia finishes her course, and her certificate arrives: *This certifies that Garcia Maria
has completed Intro to Databases.* The line that made it has eight arguments, and the compiler was
happy with every one of them. A method that asks for this much has a smell called **Long Parameter
List**.

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

{{< lesson-video youtube="Vl6_Srau7AQ" title="Long Parameter List" >}}

## Garcia Maria

Here's the call:

```java
certificates.issueCertificate(s.lastName(), s.firstName(),
        s.email(), c.title(), c.hours(), s.gradeIn(c),
        LocalDate.now(), true);
```

Can you see the wrong one? The first name and the last name are swapped. Both are strings, so
nothing complained.

## The front desk

Picture the front desk at a clinic. Every single visit, the same questions: Name? Date of birth?
Address? Phone? Insurance number? Which doctor will you see? Is this your first visit? You answer
them all, in order, every time. And one day you give your home number where they wanted your
mobile.

A parameter is one of those questions. `issueCertificate` asks eight of them, and it asks every
caller. There are eleven callers.

```mermaid {alt="The analogy mapped onto code. Each question at the front desk is a parameter. Showing your insurance card is Preserve Whole Object. We have that on file is Replace Parameter with Query. First visit, which sends you to a different desk, is a flag argument. A referral letter that bundles details is a parameter object." caption="The front desk, mapped onto the code."}
flowchart LR
  A["each question at the desk"] --> A2["a parameter"]
  B["here's my insurance card"] --> B2["Preserve Whole Object"]
  C["we have that on file"] --> C2["Replace Parameter with Query"]
  D["first visit? other desk"] --> D2["Remove Flag Argument"]
  E["the referral letter"] --> E2["Introduce Parameter Object"]
  class A2 warn
  class B2,C2,D2,E2 good
```

## The honest version

To be fair, this method grew for good reasons. Every input is right there in the signature.
Nothing is hidden. It has no hidden state, so it's easy to test: pass in values, and check the
certificate.

```java
void issueCertificate(String firstName, String lastName,
                      String email, String courseTitle,
                      int hours, int grade,
                      LocalDate issuedOn, boolean sendEmail) {
    boolean distinction = grade >= 90;
    Certificate cert = new Certificate(
            firstName + " " + lastName, courseTitle,
            hours, distinction, issuedOn);
    archive.save(cert);
    if (sendEmail) {
        mailer.send(email, cert);
    }
}
```

Fowler and Beck point out that we were taught to pass everything in, because the alternative,
global data, is worse (paraphrased). They're right. The trouble isn't that the inputs are explicit.
It's how many there are.

## Why it hurts

So what does eight cost?

**Swaps compile.** There are four strings in a row, and two integers in a row. Swap first and last
name, and you get Garcia Maria. Swap hours and grade, and the certificate says 90 hours, with no
distinction.

**The call doesn't read.** What does `true` mean at the end? You have to open the method to find
out.

**Changes ripple.** The platform wants certificates in other languages. That's a ninth parameter,
and all eleven callers change.

```mermaid {alt="One change request, certificates in Spanish, adds a ninth parameter, String language, to issueCertificate, and all eleven callers have to be edited." caption="A ninth parameter, eleven edits."}
flowchart LR
  R["certificates in Spanish"] --> P["+ String language"]
  P --> C1["caller 1"]
  P --> C2["caller 2"]
  P --> C3["caller 3"]
  P --> CN["… caller 11"]
  class R warn
  class P,C1,C2,C3,CN bad
```

## How to spot it

Start by counting. There's no magic number: refactoring.guru says more than three or four,
*Effective Java* says aim for four or fewer (Item 51, paraphrased), and Checkstyle's
`ParameterNumber` check allows seven by default. Then:

- Look for **runs of the same type**, and for **booleans**.
- Look at **where each argument comes from**. In the call above, three come out of the student and
  two come out of the course.
- Ask whether the method **could work an argument out** from the others. The grade can be worked out
  from the student and the course.

## The key insight: four questions per parameter

> **Every parameter is a question for every caller.**

So shrink the list by asking four questions of each parameter. Each question has a refactoring with
a name, and Fowler and Beck list all four for this smell.

| Question | Refactoring | In our example |
|---|---|---|
| Does the caller already hold the whole thing it comes from? | Preserve Whole Object | first name, last name, email, course title, hours |
| Can the method look it up itself? | Replace Parameter with Query | grade, issue date |
| Do some of them belong together, as one idea? | Introduce Parameter Object | (the course search, below) |
| Does one of them pick a different job? | Remove Flag Argument | `sendEmail` |

```mermaid {alt="Decision flowchart for each parameter. If the caller holds the whole object it comes from, pass the object (Preserve Whole Object). Otherwise, if the method can find it itself, drop it (Replace Parameter with Query). Otherwise, if it belongs with others as one idea, bundle them (Introduce Parameter Object). Otherwise, if it picks a different job, split the method (Remove Flag Argument). If none apply, it is an honest parameter." caption="Four questions, four refactorings."}
flowchart TD
  P["a parameter"] --> Q1{"does the caller hold<br/>the whole object?"}
  Q1 -->|yes| A1["Preserve Whole Object"]
  Q1 -->|no| Q2{"can the method<br/>look it up?"}
  Q2 -->|yes| A2["Replace Parameter with Query"]
  Q2 -->|no| Q3{"one idea with<br/>other parameters?"}
  Q3 -->|yes| A3["Introduce Parameter Object"]
  Q3 -->|no| Q4{"does it pick<br/>a different job?"}
  Q4 -->|yes| A4["Remove Flag Argument"]
  Q4 -->|no| K["an honest parameter: keep it"]
  class A1,A2,A3,A4 good
  class K muted
```

## Preserve Whole Object

Start with the whole object. The caller was unpacking the student and the course into five
arguments. Pass the two objects instead; the call becomes
`issueCertificate(s, c, s.gradeIn(c), LocalDate.now(), true)`.

```java
void issueCertificate(Student student, Course course,
                      int grade, LocalDate issuedOn,
                      boolean sendEmail) {
    boolean distinction = grade >= 90;
    Certificate cert = new Certificate(
            student.fullName(), course.title(),
            course.hours(), distinction, issuedOn);
    archive.save(cert);
    if (sendEmail) {
        mailer.send(student.email(), cert);
    }
}
```

Inside, the method takes what it needs. It reads the full name from the student itself, so there's
no name left to swap. At the front desk, that's handing over your insurance card instead of
reciting it. And the eleven callers get simpler: they pass the student and the course they already
hold. Eight parameters are down to five.

## Replace Parameter with Query

Next, look it up. The grade comes from the student and the course, and the method already has
both, so it can ask them directly. Today's date comes from the service's own clock. The clock is a
field, so a test can still fix the date.

```java
void issueCertificate(Student student, Course course,
                      boolean sendEmail) {
    boolean distinction = student.gradeIn(course) >= 90;
    Certificate cert = new Certificate(
            student.fullName(), course.title(),
            course.hours(), distinction,
            LocalDate.now(clock));
    archive.save(cert);
    if (sendEmail) {
        mailer.send(student.email(), cert);
    }
}
```

At the clinic, that's the receptionist saying: we have that on file.

One caution. Only look up what can't differ from what the caller meant. If a caller ever needs a
backdated certificate, the date is a real input, and it stays. The method looks it up, so no caller
has to. Five are down to three.

Fowler's catalog also has a sibling move, **Combine Functions into Class**: when several functions
share the same values, make those values fields of a class. That's what `clock`, `archive` and
`mailer` already are here: fields of the `Certificates` service, so no method needs them as
parameters.

## Remove Flag Argument

Last, that `true` at the end. A boolean that picks between two behaviors is really two methods,
wearing one name. It's like "first visit?" at the clinic: that answer doesn't describe your visit,
it sends you to a different desk.

So split it. `issueCertificate` makes and saves the certificate, and `emailCertificate` sends it.
Each name says what it does.

```java
Certificate issueCertificate(Student student, Course course) {
    boolean distinction = student.gradeIn(course) >= 90;
    Certificate cert = new Certificate(
            student.fullName(), course.title(),
            course.hours(), distinction,
            LocalDate.now(clock));
    archive.save(cert);
    return cert;
}

void emailCertificate(Student student, Course course) {
    mailer.send(student.email(),
            issueCertificate(student, course));
}
```

They still share the work underneath: `emailCertificate` calls `issueCertificate`, then sends the
result. Fowler's advice on [flag arguments](https://martinfowler.com/bliki/FlagArgument.html) is
exactly this: separate methods make the caller's intent plain. Now compare the calls:

```java
certificates.issueCertificate(s, c);
certificates.emailCertificate(s, c);
```

Eight arguments became two, and each line reads like a sentence.

```mermaid {alt="The refactoring path: eight parameters, then five after Preserve Whole Object, then three after Replace Parameter with Query, then two after Remove Flag Argument." caption="Eight, five, three, two."}
flowchart TD
  A["8 parameters"] -->|Preserve Whole Object| B["5"]
  B -->|Replace Parameter with Query| C["3"]
  C -->|Remove Flag Argument| D["2"]
  class A bad
  class D good
```

> **Ask only what you can't look up.**

## A second example: the course search

The fourth question needs a different example. Here's the course search, with eight parameters of
its own:

```java
interface CourseCatalog {
    List<Course> search(String text, String level,
                        int minHours, int maxHours,
                        int page, int pageSize,
                        String sortBy, boolean ascending);
}
```

No object holds these yet. But they belong together: the first four say what to find, and the last
four say which page to show. **Introduce Parameter Object** gives each idea a home: a course query
and a page spec.

```java
record CourseQuery(String text, String level,
                   int minHours, int maxHours) { }

record PageSpec(int number, int size,
                String sortBy, boolean ascending) { }

interface CourseCatalog {
    List<Course> search(CourseQuery query, PageSpec page);
}
```

And the hours from and to are a clump of their own (see [Data Clumps](/code-smells/data-clumps/)):
`minHours` and `maxHours` could become one range type. Spring Data does the same thing: its
`PageRequest.of(page, size, sort)` bundles the page number, the size and the sort into one object.

```mermaid {alt="Class diagram: CourseCatalog's search takes a CourseQuery with text, level, minHours and maxHours, and a PageSpec with number, size, sortBy and ascending." caption="Two ideas, two parameter objects."}
classDiagram
  class CourseCatalog {
    <<interface>>
    search(CourseQuery query, PageSpec page) List~Course~
  }
  class CourseQuery {
    String text
    String level
    int minHours
    int maxHours
  }
  class PageSpec {
    int number
    int size
    String sortBy
    boolean ascending
  }
  CourseCatalog ..> CourseQuery
  CourseCatalog ..> PageSpec
```

**Here's the trap.** Don't wrap all eight certificate parameters in one `CertificateParams` object.
A grab bag of eight fields asks the same eight questions, and still lets you swap them. A parameter
object should be a real idea, like a search query. Not a box for the list.

## Commonly confused: data clumps and the builder

Long parameter list has two neighbors.

- **[Data Clumps](/code-smells/data-clumps/)** is a group of values that repeats across many
  methods. A long list is one method asking too much. A clump often makes lists long, and Introduce
  Parameter Object fixes both.
- **The [Builder pattern](/patterns/builder-pattern/)**: when a constructor has many optional
  parts, a builder assembles them step by step. That's about construction. This smell is about what
  a method asks of its callers.

```mermaid {alt="Comparison: Data Clumps is a group that repeats across methods, such as minHours and maxHours; Long Parameter List is one method asking too much, such as issueCertificate with eight parameters; Builder is for constructors with many optional parts. Introduce Parameter Object fixes both of the first two." caption="Clumps repeat; long lists pile up; builders assemble constructors."}
flowchart TD
  DC["Data Clumps<br/>a group that repeats"] --> IPO["Introduce Parameter Object"]
  LPL["Long Parameter List<br/>one method asks too much"] --> IPO
  B["Builder<br/>many optional constructor parts"] --> NB["new …Builder()"]
  class IPO good
  class DC c6
  class LPL bad
```

## When it's fine

- **When the parameters keep a general function independent.** The pharmacist needs your
  prescription, not your whole file. A drawing call like `drawText(text, x, y, size)` takes four
  honest values; passing a whole `Certificate` would tie the renderer to your courses.
- **Constructors of value types list their fields.** The certificate record takes five, because a
  certificate *is* those five things:
  `record Certificate(String name, String course, int hours, boolean distinction, LocalDate issuedOn)`.
- **The number itself is a guideline.** Three, four or seven: the real question is what each
  parameter costs every caller.

## Recap

Every parameter is a question for every caller. Pass the whole object, and the pieces can't be
swapped. Let the method look up what it can. Bundle what belongs together. And split a flag into two
named methods. Keep explicit parameters where they keep things independent.

Checklist:

- Count the parameters; then look for same-type runs and booleans.
- For each argument, ask where it comes from at the call site.
- If the caller unpacks one object, pass the object.
- If the method can derive it, let it.
- If several values form one idea, give the idea a type, but never a grab bag.
- If a boolean picks the behavior, write two methods.

> **Ask only what you can't look up.**

Next in the series: [Primitive Obsession](/code-smells/primitive-obsession/). Related:
[Long Method](/code-smells/long-method/) (Introduce Parameter Object shows up there too) and
[Feature Envy](/code-smells/feature-envy/).

## Further reading

- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, "Long Parameter List".
- Refactoring catalog: [Preserve Whole Object](https://refactoring.com/catalog/preserveWholeObject.html),
  [Replace Parameter with Query](https://refactoring.com/catalog/replaceParameterWithQuery.html),
  [Remove Flag Argument](https://refactoring.com/catalog/removeFlagArgument.html),
  [Introduce Parameter Object](https://refactoring.com/catalog/introduceParameterObject.html).
- Martin Fowler, [FlagArgument](https://martinfowler.com/bliki/FlagArgument.html) (bliki).
- Joshua Bloch, *Effective Java* (3rd ed.), Item 51, "Design method signatures carefully".
