Code Smells 5 – Long Parameter Lists

Long parameter lists are very common. As method signatures change, parameter lists tend to grow. Often a method needs access to a significant amount of data to do its work. Unfortunately, long parameter lists have a lot of problems, so we need a way of avoiding them whilst still giving our method access to all the data it requires.

Why are long parameter lists a bad thing?

  1. Long parameter lists make a method signature very hard to read
  2. Long parameter lists encourage poor coding practices (See the Broken Windows Theory)
  3. Long parameter lists cause bugs – It’s very easy to get parameters the wrong way round in a method that takes 5 strings as input parameters

So how do we avoid them?

I’m going to look at 3 similar but distinct scenarios and see how we can remove the parameter from our parameter list. These are:

  1. I’m passing a field of the enclosing object as a method parameter
  2. I’m passing several pieces of data from the same object as method parameters
  3. I’m passing several related pieces of data as method parameters

Passing a field of the enclosing object as a method parameter

As a general rule, if a parameter can be obtained in another way (by referencing the object field, for example), don’t pass it as a parameter.

In this scenario, we can use the “Replace parameter with method” Refactoring. Its a good idea to run your unit tests between each step to shorten the feedback loop.

The steps are:

  1. Create a method to access the field (and unit tests)
  2. Replace every occurence of the parameter in the method with a call to the method
  3. Delete the parameter from the method signature
  4. Remove redundant code in calling methods

Passing several pieces of data from the same object as method parameters

In this case, why not pass the whole object instead? Its likely that if the method is already tied to several aspects of the object, it may require more in future. In this way, you plan ahead and reduce the chance of needing to change your method signature later.

I cover this refactoring in detail in my Preserve Whole Object article.

Passing several related pieces of data as method parameters

In this scenario, consider using a Parameter Object. A parameter object is simply an object used to represent a grouping of your data values.

I will be covering parameter objects in detail in another article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s