Order of parameters to functions

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.

This article is © Adrian Smith.
It was originally published on 8 May 2009
More on: Coding