Order of function parameters
Functions take parameters. What order should these parameters be in?
Perhaps a bit of a ridiculous question, given that it clearly doesn’t matter.
void writeUser(Connection c, User u) { ... }
void writeUser(User u, Connection c) { ... }
If one writes either of these functions, they will both work, and any performance differences between the two would be an extreme micro-optimization which wouldn’t be platform independent (e.g. in RISC OS the first 6 parameters to a C function were stored on the stack and the rest weren’t, unless one used a “pass by value” structure, so it might have an impact on performance… but I digress)
However, certain languages support the feature partial application, where passing only some of the parameters to a function produces a function taking only the remaining parameters. For example (in SML, syntax examples, BTW A sad sign of the times when Googling for SML yields “Did you mean: XML”)
fun add (a,b) = a + b; add 1 2; (* prints 3 *) val successor = add 1; (* generates function taking 1 parameter *) successor 2; (* prints 3 *)
So in those languages, it makes sense to place the most constant parameters as left-most as possible. (The syntax only allows left-most parameters to be partially applied.)
For example a function to write a user to a database connection might be defined as taking two parameters, a database connection and the user to be written, and partial application could be used as follows:
| Result of partial application | |
|---|---|
| writeUser db user | Function which writes any user to a fixed database connection |
| writeUser user db | Function which writes the particular user to any database connection |
Clearly the first partial-application function is much more useful than the second.
Even in languages which don’t support partial application I’ve noticed a convention of functions being defined this way, probably because at least some (of the best?) code is written by people with experience of functional programming languages. I like this convention, and adhere to it myself.
Perhaps a bit of a ridiculous question, given that it clearly doesn’t matter.
Not EXACTLY true, but:
place the most constant parameters as left-most as possible
is absolutely right.
Most (if not all) languages that support default parameters require the default parameters to be ‘on the right’ which are usually the optional or unimportant parameters.
OpenFile(string location, FileMode mode = FileMode.Read)
DrawImage(Buffer b, Image i, int x = 0, int y = 0)
In this case, the order DOES matter, however it still remains that the most constant (or important) parameters are required to be on the left; it *IS* a good practice to follow.