I was recently changing a method to add in an additional parameter, and I couldn’t help but wonder if there were “best practices” or “generally accepted rules” in deciding what order parameters of a method should go in? Obviously, you could put it in any order you like… I’m more wondering if there are any official (or unofficial) guidelines for this. My particular language is Java but I’m thinking this could apply to any language with arguments.
Example Parameter List:
public String generateMessage(Object o, String prefix, String suffix)
//generates a message such as: "prefix : objectName : suffix"
I am adding a boolean, which is whether the prefix should be shown.
public String generateMessage(Object o, String prefix, boolean isPrefixVisible, String suffix)
7
This question is highly subjective.
In my experience, I have found that parameter lists are clear when they meet the following criteria:
-
The primary object upon which the method or function operates comes first. In English, a sentence might contain a noun, a verb, and another noun upon which the verb could act. E.g.: “Alice sends a message.” In OO parlance, “Alice” could be the object to which the method belongs. “Sends” could be the method itself, and “a message” is its parameter:
alice.sends(message)
. Maybe there are other parameters, but they should read roughly like a sentence: “Alice sends a message, but gives up after 30 seconds if nobody listens.”alice.sends(message, 30)
. It is natural, our brains are already trained to think this way from an early age. -
If there are more than (insert subjective number here, maybe four or five) parameters, break up the method call somehow. Maybe there is an object (e.g. builder) screaming to be refactored out. If a parameter list is long enough that you have to ask this question, it is already long enough to be difficult to understand.