Reputation: 435
Assuming they are all mandatory:
function search (haystack, needle)
function search (needle, haystack)
function placeObject (object, column, row)
function placeObject (column, row, object)
function newObject (parent, width, height, isVisible)
function newObject (isVisible, width, height, parent)
function newObject (width, height, isVisible, parent)
I think it is often a matter of personal choice which should be consistent throughout the project. But I wonder whether there is a deeper logic which would dictate the order for every case.
Upvotes: 5
Views: 141
Reputation: 363627
Try to pronounce the intended invocation.
function search (needle, haystack)
Search for needle in haystack.
function placeObject (object, column, row)
Place object at (column, row).
newObject
is tough: try to keep it consistent with your framework, if any, put the common parameters first. I'd put isVisible
last just because it's boolean, and it can be hard to infer from a boolean literal what it does. With multiple booleans, I prefer to combine them into a flags object of integer type, built with bitmasks (or a key-value dictionary, or a string, depending on the language) to obtain readability:
openFile(path, READ | LOCKED | COMPRESSED | ...)
Upvotes: 1
Reputation: 2414
I have a feeling the usual logic is a function of time. You see, if you have a function:
public Pizza makePizza(cheese, sauce){}
And then you make a variable that determines a topping number in an array:
int toppingNo = 3;
You probably want to send that to your function as well, right?
public Pizza makePizza(cheese, sauce, topping){}
And that, my son, is how parameters are born!
Sarcasm aside, that's how I always did it, unless you have parameters that clearly need to be grouped due to their similarities, such as a coordinate system.
Upvotes: 0
Reputation: 72765
I can think of a few things although none are "rules". They're just things I find convenient.
Consistency. If you have, for example, functions that copy objects, then be consistent with the order in which source and destination are specified. You can exploit existing biasses which people might have (e.g., the order of operands in the assembler MOV
directive or the order arguments to the C standard library strcmp
function).
Grouping. It's useful to put things that are logically "grouped" together. e.g. If your function is opening a connection to a database, username and password should be together (and probably in that order as well).
Readability. The "large" parameters on which operations take place should precede the smaller ones. e.g. draw_line(canvas, x0, y0, x1, y1)
rather than draw_line(x0, y0, x1, y1, canvas)
.
It's also useful to think of the function as a prefix operator on it's arguments and then try to convert it into infix to see what's natural.
If your language supports keyword arguments, it's usually a good idea to use them (unless it's glaringly obvious what the arguments and order should be).
Upvotes: 0