当前位置: 动力学知识库 > 问答 > 编程问答 >

language agnostic - Guidelines for listing the order of function arguments

问题描述:

Are there any rules that you follow to determine the order of function arguments? For example, float pow(float x, float exponent) vs float pow(float exponent, float x). For concreteness, C++ could be used, but the question is valid for all programming languages.

My main concern is from the usability point of view, not runtime performance.

Edit:

Some possible bases for ordering could be:

  • Inputs versus Output
  • The way a "formula" is usually written, i.e., arguments from left-to-write.
  • Specificity to the argument to the context of the function, i.e., whether it is a "general" argument, e.g., a singleton object of the system, or specific.

网友答案:

In the example you cite, I think the order was decided on the basis of the mathematical notation xexponent, in which the base is written before the exponent and becomes the left parameter.

I'm not aware of any really sound general principle other than to try to imagine what your users will expect and/or easily remember. People aren't even wholly agreed whether you should write (source, destination) or (destination, source) when copying (compare std::copy with std::memcpy), although I'm pretty sure that the former is now much more common.

There are a whole lot of general conventions, though, followed to different extents by different people:

  • if the function is considered primarly to act upon a particular object, put it first
  • parameters that are considered to "configure" the operation of the function come after parameters that are considered the main subject of the function.
  • out-params come last (but I suspect some people follow the reverse)

To some extent it doesn't really matter -- namely the extent to which your users have IDEs that tell them the parameter order as they type the function name.

分享给朋友:
您可能感兴趣的文章:
随机阅读: