Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make long parameter lists readable?

I've developed a natural aversion to long parameter lists in functions. While this is to some extent a good thing, sometimes long parameter lists are the lesser of two evils compared to code duplication or ridiculously long functions due to "manual inlining". What's a good way to at least make some of these monstrosities human-readable? For example:

SomeClass[string] someFunction(SomeClass!(TemplateParam) foo, 
    string[][string] someAA, uint[] dataToProcess, SomeEnumType flag) {
    // Do stuff.
}

This doesn't score high on the readability scale, but four parameters is pretty reasonable in a lot of cases.

like image 382
dsimcha Avatar asked Jan 28 '10 17:01

dsimcha


People also ask

How do you deal with a long parameter list?

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.

How do you specify a parameter list?

The method's parameter list must not contain a rest value declaration. The two parameter lists must contain the same number of required value declarations. Each value type in the method's parameter list must be a subtype of the corresponding value type in the generic function's parameter list.

How do you reduce the number of arguments in Java?

Well, if a method has five or more parameters, then you should consider refactoring that method and decreasing the number of parameters. This is where Introduce Parameter Object refactoring comes into play. In short, this refactoring is a way of replacing a method's argument list with a single parameter object.


2 Answers

For this kind of situation, I tend to format it like this:

SomeClass[string] someFunction(
    SomeClass!(TemplateParam) foo, 
    string[][string] someAA,
    uint[] dataToProcess,
    SomeEnumType flag
)
{
    // Do stuff.
}
like image 191
Aaron Avatar answered Sep 18 '22 01:09

Aaron


  • for the sake of readability - put each argument on new line
  • for the sake of usability and better API desgin - group related arguments into new classes, thus shortening the number of arguments.
like image 44
Bozho Avatar answered Sep 22 '22 01:09

Bozho