Say I have a function taking three arguments:
a symbol (an alias for a class, method or function name)
a mirror/reflection of a specific object
a mirror/reflection of a class in general
is there a how-to (e.g. for certain languages or libraries) to sort things in function calls to keep an API consistent?
3
That pretty much depends on your API / environment.
A few rules and guidelines that I know of:
- In general: POLA – Principle of Least Astonishment (first brought to Computer Science by Mike Colishaw in his book the Rexx Programming Language), also known as Rule of Least Surprise – try to think from an API user’s perspective, how is it easy to remember? How is it natural to read? Avoid astonishment / surprise.
- Place cohesive arguments together. Example: In
arraycopy(src, srcOffset, dst, dstOffest, length)
,src
andsrcOffset
are very cohesive, so they stay together.length
is also cohesive tosrc
, but it is equally cohesive todst
, which makes the cohesion less specific, therefore it comes last. - Place the primary object first, i.e. the object that would be a
this
reference in an OO language. In other words: Place the object “to which the operation is told” first. - Place the destination before the source (C and similar languages).
- Place the source / input before the destination / output (Java and similar languages).
- Place those arguments that are more likely to vary between similar function calls more to the right, those arguments that are more likely to stay the same more to the left.
- Place the parameters with more generic meaning more to the left, the ones with more specific meaning more to the right. For example:
(directory, file)
is usually more logical than(file, directory)
– unlessdirectory
is a destination. Orclass, object
usually is more logical thanobject, class
– unlessobject
is ofthis
nature. - Try to make the calls read (almost) like well-written prose.
And a few hints:
- Be consistent within your API.
- Make it easy for users which already know similar APIs, i.e. look around. If you develop a Qt extension, look how the Qt API itself feels. If you develop a Java API, look how the SUN / Oracle Java API looks and feels.
A few more examples:
- If a function takes an array, an offset into that array, and a length, the sequence should be
(array, offset, length)
because that’s how you think: First what, then the details, and the details in the sequence in which they matter. The contract is probably about iteration which we expect to start atoffset
and run untillength
is reached.
In your case it depends on the nature of the symbol, the object and the class. If I assume that object is a member of class, and symbol is a member of object, I would probably expect the sequence to be (class, object, symbol)
.