Methods with many parameters are often sometimes unavoidable. In my own experience I often find this is the case for program entry points and complex mathematical procedures - where refactoring is either not possible, or would obscure the meaning of the method. Although there are no concrete limits for the number of parameters a method might have, it is patently undesirable to write/maintain/see methods with a large number of parameters.
An alternative is wrapping parameters into classes. This has some clear advantages, including:
- Easier on the eye; nobody likes parameter fishing.
- Easier maintenance; changing the parameters does not require modification to the method declaration.
- Better typing; wrapping related parameters together into a single type can help clarify the meaning of the function.
However, there are several disadvantages to this approach:
- Worse typing; coupling parameters that do not naturally fit together can be misleading.
- Overloading becomes either impossible or messy.
- Can impose unwanted foreign types on users.
- Can lead to laziness.
For example: I've often seen Python code where the author repeatedly passes around objects generated by optparse
(or argparse
) whilst only using a small subset of the parameters in each method.
At the sake of brevity, here are the options:
my_method(Param1 a, Param2 b, Param3 c, ...., ParamInf zzz)
my_method(Params params)
my_method(Param1 a, Param2 b, Param3 c, SomeParams the_rest)
my_method(ParamSetA a, ParamSetB b, ...)
Whilst this is a somewhat subjective subject, I am interested to hear strategies for dealing with methods with large numbers of parameters. Real-life examples - especially those that have undergone code review - would be especially helpful.
my_method
examples are all named bad. The point here is, that putting multiple parameter into one or multiple parameter set or list is per se not a good idea. It only is a good idea if these parameters belong together. It should then not be a list but its own class (as you said). I also think your disadvantages are not valid, except the last maybe (which can't be helped anyways). I would like you to further explain the drawbacks, e.g. what you mean with "unwanted foreign types" or in which case overloading would become impossible or messy (while still beeing semantically correct).