samedi 24 janvier 2015

Strategies for parameter wrapping


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.





Aucun commentaire:

Enregistrer un commentaire