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?
- Long parameter lists make a method signature very hard to read
- Long parameter lists encourage poor coding practices (See the Broken Windows Theory)
- 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:
- I’m passing a field of the enclosing object as a method parameter
- I’m passing several pieces of data from the same object as method parameters
- 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:
- Create a method to access the field (and unit tests)
- Replace every occurence of the parameter in the method with a call to the method
- Delete the parameter from the method signature
- 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.