Suppose I have the following
Class A {
Foo getFoo();
Bar getBar();
Baz getBaz();
}
And I need to define a function doStuff
Parameter Object
s do provide a nice approach to encapsulate related
parameters to reduce the total parameter count to any method or constructor.
One should be very careful to make sure that the parameter objects do actually contain truly related parameters.
Actually there are multiple ways of approaching this problem depending on the parameter types
you are dealing with.
If you are dealing with parameters that are general types like more than one String
s or Int
s and there is a potential for a client to actually pass in the wrong sequence of arguments ,it often makes more sense to create custom types
ie. create enum
with possible values. That can provide good compile time check for your arguments.
Another good use of them is you can use them to return
complex values from functions. See here.
Another approach i take a lot of times is to check and see if the work done by the doStuff
method be broken down into simpler methods with less dependencies.
Principally i try to follow Bob Martin's recommendation of a maximum of three parameters. Well he actually say it should be mostly not more than one ! Any increase should have justified reasons. Refer this excellent book : Clean Code