Programming Search⌘K

Patterncore

Long Parameter List

Also called too many parameters, too many arguments.

A code smell: a function takes so many parameters that a caller cannot tell which argument is which, and a swapped pair of arguments of the same type is a bug that the compiler does not catch.

Family
code-smell
Intent
Find the functions with more parameters than a caller can keep in mind, and pass fewer values that each mean more.

Intent

Find the functions that take more parameters than a caller can keep in mind, and change them so that they take fewer values, each with a clear meaning.

Problem

A call such as stayPrice(10, 13, 8000, 1500, 2, true) shows six values and no names. The reader of the call must open the definition to learn that the third value is the price of a night and the fourth is the price of a breakfast. The writer of the call must get the order right. When two parameters have the same type, a swapped pair is still a valid call, and the program computes a wrong result.

The forces are these:

  • Refactoring says that early programmers were taught to pass everything a function needs as parameters, because the alternative was global data. That advice is still sound, but the parameter lists then grow, and long lists are confusing in their own right.1
  • Many parameters often go together: a start and an end, an x and a y, a currency and an amount. Each pair is a concept that has no name in the code.
  • A boolean parameter makes one function do two things, and the call site does not say which one. true means nothing at the place where it is written.
  • Each added parameter changes every call. A function with many callers and a growing list of parameters is expensive to change.

The Pylint documentation for too-many-positional-arguments puts it in one line: "For almost all interfaces, comprehensibility suffers beyond a handful of arguments." It also names a fair exception, rgba(1.0, 0.5, 0.3, 1.0), where the order follows a convention that all readers know.2

Solution

Refactoring gives five refactorings, each for a different cause of the long list.1 The catalogue at refactoring.com has a card for each.3

  1. A parameter that the function can compute from another one. Replace Parameter with Query removes it, and the function asks for the value itself.
  2. Several fields taken out of one object and passed one by one. Preserve Whole Object passes the object.
  3. Parameters that always travel together. Introduce Parameter Object makes a type for them, such as a date range.
  4. A boolean that selects the behaviour. Remove Flag Argument makes one function for each value of the flag.
  5. Several functions that share the same parameters. Combine Functions into Class stores the shared values as fields, and the functions read them from there.

A parameter object is often the first step to a better design. Once the start and the end are one DateRange, the code that computes the number of nights can move into it.

Example

The function computes the price of a hotel stay. It takes six parameters: two days, two prices, the number of guests and a flag for breakfast. The test shows that a call with the two prices swapped runs and gives a wrong price.

import assert from "node:assert/strict";

// Before: six positional parameters.
function stayPriceBefore(startDay, endDay, nightlyRate, breakfastRate, guests, withBreakfast) {
  const nights = endDay - startDay;
  let price = nights * nightlyRate;
  if (withBreakfast) price += nights * guests * breakfastRate;
  return price;
}

// After: a date range, the room as a whole, and a stay that holds the rest.
const nights = (range) => range.end - range.start;

function stayPrice(stay, room) {
  const n = nights(stay.range);
  const breakfast = stay.breakfast ? n * stay.guests * room.breakfastRate : 0;
  return n * room.nightlyRate + breakfast;
}

const room = { nightlyRate: 8000, breakfastRate: 1500 };
const stay = { range: { start: 10, end: 13 }, guests: 2, breakfast: true };

assert.equal(stayPriceBefore(10, 13, 8000, 1500, 2, true), 33000);
assert.equal(stayPriceBefore(10, 13, 1500, 8000, 2, true), 52500); // swapped, and no error
console.log("stayPriceBefore: tests pass");

assert.equal(stayPrice(stay, room), 33000);
assert.equal(stayPrice({ ...stay, breakfast: false }, room), 24000);
console.log("stayPrice: tests pass");
Output
stayPriceBefore: tests pass
stayPrice: tests pass

Three nights at 80.00 cost 240.00, and breakfast for two guests on three mornings at 15.00 costs 90.00, so the price is 330.00. With the prices swapped, the old function returns 525.00. In the second version the caller writes nightlyRate and breakfastRate by name, once, in the room object, so that mistake has no place to happen.

Language What the example shows
JavaScript the parameter objects above, as object literals
Python the same objects as frozen dataclasses, and keyword-only parameters as a lighter fix
Java records for the range, the room and the stay
Go structs, and a composite literal with field names at the call site
PythonGitHub
from dataclasses import dataclass, replace


# Before: six positional parameters.
def stay_price_before(start_day, end_day, nightly_rate, breakfast_rate, guests, with_breakfast):
    nights = end_day - start_day
    price = nights * nightly_rate
    if with_breakfast:
        price += nights * guests * breakfast_rate
    return price


# After: a date range, the room as a whole, and a stay that holds the rest.
@dataclass(frozen=True)
class DateRange:
    start: int
    end: int

    def nights(self):
        return self.end - self.start


@dataclass(frozen=True)
class Room:
    nightly_rate: int
    breakfast_rate: int


@dataclass(frozen=True)
class Stay:
    range: DateRange
    guests: int
    breakfast: bool


def stay_price(stay, room):
    n = stay.range.nights()
    breakfast = n * stay.guests * room.breakfast_rate if stay.breakfast else 0
    return n * room.nightly_rate + breakfast


# A lighter fix: keyword-only parameters, so that each call names its values.
def stay_price_kw(*, start_day, end_day, nightly_rate, breakfast_rate, guests, with_breakfast):
    return stay_price_before(start_day, end_day, nightly_rate, breakfast_rate, guests, with_breakfast)


assert stay_price_before(10, 13, 8000, 1500, 2, True) == 33000
assert stay_price_before(10, 13, 1500, 8000, 2, True) == 52500  # swapped, and no error
print("stay_price_before: tests pass")

room = Room(nightly_rate=8000, breakfast_rate=1500)
stay = Stay(DateRange(10, 13), guests=2, breakfast=True)
assert stay_price(stay, room) == 33000
assert stay_price(replace(stay, breakfast=False), room) == 24000
print("stay_price: tests pass")

assert stay_price_kw(start_day=10, end_day=13, nightly_rate=8000,
                     breakfast_rate=1500, guests=2, with_breakfast=True) == 33000
try:
    stay_price_kw(10, 13, 8000, 1500, 2, True)
except TypeError:
    print("stay_price_kw: positional call rejected")
else:
    raise AssertionError("positional call accepted")
Output
stay_price_before: tests pass
stay_price: tests pass
stay_price_kw: positional call rejected
  • DateRange.nights shows the next step after Introduce Parameter Object: the behaviour that belongs to the range moves into it.
  • dataclasses.replace makes a copy of a frozen dataclass with one field changed, which the test uses to turn breakfast off.
  • The keyword-only version keeps the six parameters, but a call with the values in the wrong order cannot be written by accident, because each value has its name next to it.
JavaGitHub
public class Main {
    // Before: six positional parameters.
    static long stayPriceBefore(int startDay, int endDay, long nightlyRate, long breakfastRate,
                                int guests, boolean withBreakfast) {
        int nights = endDay - startDay;
        long price = nights * nightlyRate;
        if (withBreakfast) price += (long) nights * guests * breakfastRate;
        return price;
    }

    // After: a date range, the room as a whole, and a stay that holds the rest.
    record DateRange(int start, int end) {
        DateRange {
            if (end < start) throw new IllegalArgumentException("end before start");
        }
        int nights() { return end - start; }
    }

    record Room(long nightlyRate, long breakfastRate) {}

    record Stay(DateRange range, int guests, boolean breakfast) {}

    static long stayPrice(Stay stay, Room room) {
        int n = stay.range().nights();
        long breakfast = stay.breakfast() ? (long) n * stay.guests() * room.breakfastRate() : 0;
        return n * room.nightlyRate() + breakfast;
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        check(stayPriceBefore(10, 13, 8000, 1500, 2, true) == 33000, "before");
        check(stayPriceBefore(10, 13, 1500, 8000, 2, true) == 52500, "swapped, and no error");
        System.out.println("stayPriceBefore: tests pass");

        Room room = new Room(8000, 1500);
        Stay stay = new Stay(new DateRange(10, 13), 2, true);
        check(stayPrice(stay, room) == 33000, "after");
        check(stayPrice(new Stay(stay.range(), 2, false), room) == 24000, "no breakfast");
        System.out.println("stayPrice: tests pass");
    }
}
Output
stayPriceBefore: tests pass
stayPrice: tests pass
  • A record declares its fields, its constructor and its accessors in one line. The compact constructor of DateRange checks the range once, where the old version had no place to put the check.
  • stayPrice(room, stay), with the arguments swapped, does not compile, because a Room is not a Stay. The swap of two long values in the old version compiles.
  • Java has no named arguments, so new Room(8000, 1500) still depends on the order. The risk is now in one constructor call, not in each call to the price function.
package main

import "fmt"

// Before: six positional parameters.
func stayPriceBefore(startDay, endDay, nightlyRate, breakfastRate, guests int, withBreakfast bool) int {
	nights := endDay - startDay
	price := nights * nightlyRate
	if withBreakfast {
		price += nights * guests * breakfastRate
	}
	return price
}

// After: a date range, the room as a whole, and a stay that holds the rest.
type dateRange struct{ start, end int }

func (r dateRange) nights() int { return r.end - r.start }

type room struct{ nightlyRate, breakfastRate int }

type stay struct {
	dates     dateRange
	guests    int
	breakfast bool
}

func stayPrice(s stay, r room) int {
	n := s.dates.nights()
	price := n * r.nightlyRate
	if s.breakfast {
		price += n * s.guests * r.breakfastRate
	}
	return price
}

func main() {
	if stayPriceBefore(10, 13, 8000, 1500, 2, true) != 33000 ||
		stayPriceBefore(10, 13, 1500, 8000, 2, true) != 52500 { // swapped, and no error
		panic("before")
	}
	fmt.Println("stayPriceBefore: tests pass")

	r := room{nightlyRate: 8000, breakfastRate: 1500}
	s := stay{dates: dateRange{start: 10, end: 13}, guests: 2, breakfast: true}
	noBreakfast := s
	noBreakfast.breakfast = false
	if stayPrice(s, r) != 33000 || stayPrice(noBreakfast, r) != 24000 {
		panic("after")
	}
	fmt.Println("stayPrice: tests pass")
}
Output
stayPriceBefore: tests pass
stayPrice: tests pass
  • Go has no named arguments, but a composite literal can name its fields: room{nightlyRate: 8000, breakfastRate: 1500}. The names at the call site do the work that keyword arguments do in Python.
  • A struct is a value in Go, so noBreakfast := s copies the stay, and the change to the copy does not change s.
  • The old signature has five parameters of type int, so the compiler accepts them in any order. The structs remove that risk.

Consequences

The calls become shorter and they name their values. The parameter objects are types that the compiler can check: in Java and Go, a Room cannot be passed where a DateRange is expected. Behaviour that belongs to the group, such as the number of nights, gets a home.

The cost is more types. A parameter object for one call is overhead, and a reader must look in two places to see what a function receives. Preserve Whole Object also adds a dependency: the function now depends on the type of the whole object, not on two numbers, so it cannot be called without one. The first edition of Refactoring names this as the exception to Preserve Whole Object: the case where the called code should not depend on the larger object.4

Some languages reduce the problem without an added type. Python can make parameters keyword-only with a * in the definition, so that each call must name its arguments. The Python tutorial advises keyword-only parameters "when names have meaning and the function definition is more understandable by being explicit with names".5 The Pylint example for too-many-positional-arguments uses this fix.2 The example for too-many-arguments uses the other fix: a dataclass that groups the coordinates of a chess piece.6 In Java, a record is a short way to declare a parameter object with its fields, constructor and accessors.7

Linters set a limit on the count. Their defaults differ widely:

Tool Rule Default limit
ESLint max-params 3 parameters8
Pylint too-many-arguments (max-args) 5 arguments9
Pylint too-many-positional-arguments (max-positional-arguments) 5 positional arguments9
Checkstyle ParameterNumber 7 parameters10

How to fix it

Data Clumps. The same group of values in many parameter lists and many classes. A parameter object is the fix for both smells. See Data Clumps.

Flag argument. A boolean parameter that selects one of two behaviours. See Boolean parameter.

Primitive Obsession. Six numbers in a row are often six primitives that should be two or three types. See Primitive Obsession.

Builder. When a constructor has many optional parameters, the Builder pattern sets them one by one with named methods. See Builder.

Global Data. The old alternative to many parameters, with worse problems. See Global Data.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Long Parameter List
  2. Pylint documentation, too-many-positional-arguments / R0917, Description, Correct code and Additional details
  3. Martin Fowler, Catalog of Refactorings, the cards Replace Parameter with Query, Preserve Whole Object, Introduce Parameter Object, Remove Flag Argument and Combine Functions into Class
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Long Parameter List, the exception for a dependency on the larger object
  5. The Python Tutorial, More Control Flow Tools, Python 3.14, 4.9.3 Special parameters, 4.9.3.3 Keyword-Only Arguments and 4.9.3.5 Recap
  6. Pylint documentation, too-many-arguments / R0913, Description and Correct code
  7. The Java Language Specification, Java SE 25 Edition, 8.10 Record Classes
  8. ESLint documentation, Rules, max-params, Options, max (default 3)
  9. Pylint documentation, All configuration options, Design checker, --max-args (default 5) and --max-positional-arguments (default 5)
  10. Checkstyle documentation, ParameterNumber, Properties, max (default 7)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B3W15R/text.yaml