Code Smell: Long Parameter List

Software Design

Long parameter list in a method call is a code smell. It indicates that there might be something wrong with the implementation.

There is no single rule for how many is too many parameters. Usually more than three or four is considered too many. Here is explained why and how to refactor such cases.

Symptoms

A long parameter list is easy to spot. Symptoms of too many parameters include:

Consider the following example:

calculateStatistics(customer, unit, null, true, false);

It is not really clear what each parameter does. To find out you are forced to read the documentation.

Causes

There is usually a cause for the symptoms described. Maybe you needed more data in a method. Maybe you tried to make a method generic and handle different scenarios. Having a long parameter list can come down to:

Solutions

Depending on the situation there are different ways to make it better. These simple techniques show how to refactor the code in each case. Keep in mind that the examples are very simple on purpose!

Replace parameter with method call

Before:

int price = quantity * itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice(price, discountLevel);

After:

int basePrice = quantity * itemPrice;
double finalPrice = discountedPrice(basePrice);

Preserve whole object

Before:

int x = point.getX();
int y = point.getY();
window.setLocation(x, y);

After:

window.setLocation(point);

Introduce parameter object

Before:

account.balanceBetween(startDate, endDate);

After:

account.balanceBetween(new DateRange(startDate, endDate));

Replace parameter with explicit methods

Before:

setValue("visible", true);

After:

show();

Benefits

These kind of changes are not made just for fun. Benefits of refactoring include:

Exceptions

This code smell is something that does not guarantee a problem. Sometimes you might decide to go with a long parameter list.

Summary

Long parameter list makes the code harder to use and understand.

Long parameter list can be caused by too complex methods. Another reason is avoiding dependencies.

One way to reduce number of parameters is to replace a parameter with a method call. You can also preserve a whole object or introduce a parameter object. Another way of reducing parameters is replacing a parameter with explicit methods.

Refactoring makes the code easier to read. It may also help to get rid of duplication.

code-smells