Long Parameter List

November 25, 20268 minutes

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

Garcia Maria

Here’s the call:

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.

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. 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.
The front desk, mapped onto the code.

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.

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.

One change request, certificates in Spanish, adds a ninth parameter, String language, to issueCertificate, and all eleven callers have to be edited. One change request, certificates in Spanish, adds a ninth parameter, String language, to issueCertificate, and all eleven callers have to be edited.
A ninth parameter, eleven edits.

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.

QuestionRefactoringIn our example
Does the caller already hold the whole thing it comes from?Preserve Whole Objectfirst name, last name, email, course title, hours
Can the method look it up itself?Replace Parameter with Querygrade, 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 ArgumentsendEmail
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. 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.
Four questions, four refactorings.

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

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.

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.

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 is exactly this: separate methods make the caller’s intent plain. Now compare the calls:

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

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

The refactoring path: eight parameters, then five after Preserve Whole Object, then three after Replace Parameter with Query, then two after Remove Flag Argument. The refactoring path: eight parameters, then five after Preserve Whole Object, then three after Replace Parameter with Query, then two after Remove Flag Argument.
Eight, five, three, two.

Ask only what you can’t look up.

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

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.

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): 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.

Class diagram: CourseCatalog's search takes a CourseQuery with text, level, minHours and maxHours, and a PageSpec with number, size, sortBy and ascending. Class diagram: CourseCatalog's search takes a CourseQuery with text, level, minHours and maxHours, and a PageSpec with number, size, sortBy and ascending.
Two ideas, two parameter objects.

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 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: 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.
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. 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.
Clumps repeat; long lists pile up; builders assemble constructors.

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. Related: Long Method (Introduce Parameter Object shows up there too) and Feature Envy.

Further reading