What conventions exist for ordering arguments in methods?

My colleague and I discuss best practices regarding order method parameters. The goal is to set the standard in our organization to improve readability and performance by providing common signatures to our methods. We just make recommendations for the recent graduates we hire.

Example (userId is always passed to audit calls):

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

My argument is as follows:

  • most common arguments are common.
  • other arguments are based on importance
  • optional (null) arguments to last.

His argument is essentially the opposite.

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

Thanks!

+6
oop coding-style
source share
5 answers

I would go with ordering input, output, optional.

It is not necessary to go to me, because most languages โ€‹โ€‹allow you to specify a default value for optional arguments, so as not to include them. This means that they must be the last argument, otherwise you will not be able to drop them.

Suppose you cannot have named arguments. If you can have them, I always suggest using them for clarity, and the order becomes controversial.

+6
source share

I am trying to use all methods that use similar parameters in the same order.

For choice for one method, I go by importance. Optional last elements.

+4
source share

I like to sort them alphabetically by name. This makes it easier to find the one you are looking for.

I agree that optional values โ€‹โ€‹with default values โ€‹โ€‹seem to belong to the end. In some languages โ€‹โ€‹this is required.

When you have overloaded methods, I start with the most commonly used argument and end with those who 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) 
+3
source share

One idiom popular in C programming is that the goal comes first, so in strcpy (A, B); copies B to (like "A = B", copies B to A).

+1
source share

Order items in other contexts.

The easiest way to add arguments to the end.

+1
source share

All Articles