Sometimes (rarely), it seems that creating a function that takes a decent amount of parameters is the best route.
Using several parameters is often a clear indicator, that you violate the SRP in this method. A method, which needs many parameters is unlikely to do only one thing. Excpetion may be a mathematical function or a configuration method, where indeed several parameters as such are needed. I would avoid multiple parameters as the devil avoids the holy water. The more parameters you use within a method, the higher the chance, that the method is (too) complex; the more complexity means: harder to maintain and that is less desirable.
However, when I do, I feel like I'm often choosing the ordering of the parameters at random. I usually go by "order of importance", with the most important parameter first.
In priniple you are choosing at random. Of course you might think paramter A is more relevant than parameter B; but that might not be the case for users of your API, who think B is the most relevant parameter. So even if you were attentive in choosing the ordering - for others it could seem random.
Is there a better way to do this? Is there a "best practice" way of ordering parameters that enhances clarity?
There are several ways out:
a) The trivial case: Do not use more than one parameter.
b) As you did not specify, what language you've chosen, there is the chance, that you chose a language with named parameters.
This is nice syntactic sugar which allows you to loosen the significance of the ordering of paramters: fn(name:"John Doe", age:36)
Not every language allows such niceties. So what then?
c) You could use a Dictionary/Hashmap/Associative Array as parameter:
e.g. Javascript would allow the following: fn({"name":"John Doe", age:36})
which is not far away from (b).
d) Of course if you work with a statically typed language like Java. you could use a Hashmap, but you would loose typeinformation (e.g. when working with HashMap<String, Object>
) when parameters have different types (and need to cast).
The next logical step would be to pass an Object
(if you are using Java) with appropriate properties or something more lightweight like a struct (if you write e.g. C# or C/C++).
Rule of thumb:
1) Best case - your method needs no parameter at all
2) Good case - your method needs one parameter
3) Tolerable case - your method needs two parameters
4) All other cases should be refactored
MessageBox.Show
. Look into that as well.