views:

152

answers:

5

A colleague and I are discussing best practices regarding ordering method parameters. The goal is to establish a standard in our organization to improve readability and productivity by giving our methods common signatures. We are merely establishing guidelines for the recent grads we are hiring.

Example (userId is always passed in to audit the calls):

GetOrders(string userId, int customerId); GetOrders(string userId, int[] orderIds); GetCustomer(string userId, int customerId);

My argument is the following:

  1. common arguments are left most.
  2. remaining arguments are based on importance
  3. optional (nullable) arguments last.

His argument is essentially the opposite.

I'm not asking for a right or wrong answer here, nor a discussion. I just want to see what standards exist already.

Thanks!

+6  A: 

I'd go with the ordering of input,output,optional.

Optional should go at the end to me because most languages allow you to specify a default value for optional arguments to avoid having to include them. The provision of that is that they have to be the last argument(s) otherwise you can't drop them.

That's assuming you can't have named arguments though. If you can have them, I'd always suggest using them for clarity and order becomes a moot point.

workmad3
+3  A: 

I like arranging them in alphabetical order, by name. Makes it easier to locate the one you seek.

I agree that optional ones with default values seem to belong at the end. In some languages, this is required.

When you have overloaded methods, I would start with the most commonly used argument, and end up with the one(s) that make this version of the method unique.

public method foo (string name)
public method foo (string name, string city)
public method foo (string name, string city, string state)
DOK
+1 for the recommendation for overloaded methods. Disagree with alphabetical order though.
OregonGhost
Yeah, I don't feel strongly about alphabetizing. What's your preference?
DOK
+4  A: 

I try to make all methods that use similar parameters use them in the same order.

For the choice for a single method, I go by importance. Optional items last.

BlackWasp
+1  A: 

One idiom popular in C programming, is that the target goes first, so that in strcpy(A, B); is copying B to A (much like "A=B;" is copying B to A).

James Curran
bcopy uses the opposite: void bcopy(const void *s1, void *s2, size_t n);
philippe
+1  A: 

Order the things appear in other contexts too.

It is easiest to add arguments to the end.

iny