函数声明是否应包含参数名称?

Sim*_*Sim 22 c++ coding-style

您实际上会考虑更好的编码风格:在标题内声明函数/方法的参数名称,或仅在源文件中声明参数名称,因为可以同时执行这两种操作:如果您实际上只考虑在源文件中声明函数/方法的参数名称,那么您将如何声明默认值?

外标题:

//One.hpp
#ifndef ONE_HPP
#define ONE_HPP
namespace eins {

/** \brief description
 *  
 * \param one represents ....
 * \param two represents ....
 */
void function(int,int);

}
#endif

// One.cpp
#include "One.hpp"

eins::function(int one,int two) {
  //Do stuff//
}
Run Code Online (Sandbox Code Playgroud)

内部标题:

//One.hpp
#ifndef ONE_HPP
#define ONE_HPP
namespace eins {

/** \brief description
 *  
 * \param one represents ....
 * \param two represents ....
 */
void function(int one,int two);

}
#endif

// One.cpp
#include "One.hpp"

eins::function(int one,int two) {
  //Do stuff//
}
Run Code Online (Sandbox Code Playgroud)

我个人的观点是第一种方式更好,因为用户实际上被迫阅读注释/ API,并且不能误导只读取参数名称.但我不确定这一点,实际上声明默认值会破坏我的风格,因为你必须在函数/方法的头声明中这样做.

Bee*_*San 27

虽然两者都很好并且使用了很多,但在头文件的声明中使用参数名称有明显的优势.

大多数文档系统(比如doxygen)都会解析您的头文件并生成文档.举个例子,请看这里:http://libface.sourceforge.net/doc/html/classlibface_1_1_face.html

查看构造函数文档.

比较一下

Parameters:
    x1  X coordinate of the top left corner of the face.
    y1  Y coordinate of the top left corner of the face.
    x2  X coordinate of the bottom right corner of the face.
    y2  Y coordinate of the bottom right corner of the face.
    id  ID of the face. -1 not not known.
    face    A pointer to the IplImage with the image data. 
Run Code Online (Sandbox Code Playgroud)

还有这个

Parameters:
    param1  X coordinate of the top left corner of the face.
    param2  Y coordinate of the top left corner of the face.
    param3  X coordinate of the bottom right corner of the face.
    param4  Y coordinate of the bottom right corner of the face.
    param5  ID of the face. -1 not not known.
    param6  A pointer to the IplImage with the image data. 
Run Code Online (Sandbox Code Playgroud)

你明白了.:)


Joh*_*McG 10

在声明中包含参数名称.

最好以尽可能紧凑的格式为其他开发人员提供尽可能多的信息.强迫他们查看注释以确定简单的参数是什么,这可能会使他们脱离流程,使他们的工作效率降低,并使他们感到沮丧.


Kei*_*son 5

您应该努力为您的函数命名,以便它们不需要包含参数名称就可以清楚地了解它们的作用。如果你看到一个方法原型:

void save(const std::string&);
Run Code Online (Sandbox Code Playgroud)

它在做什么?是保存那个字符串吗?或者它是否保存到由字符串表示的文件路径?或者...?

所以你可以这样做:

void save(const std::string& filepath);
Run Code Online (Sandbox Code Playgroud)

澄清。但这只有在有人查看标题时才会澄清。如果你这样做:

void saveToFilepath(const std::string&);
Run Code Online (Sandbox Code Playgroud)

到处都应该很清楚。当然,随着您添加更多参数,这会变得更加麻烦(但这是不添加太多参数的另一个原因;请参阅 Bob Martin 的Clean Code对此;他推荐空函数和一元函数,对二元函数犹豫不决,对三元函数,并且不愿意更多)。

所以我的建议是努力没有理由在你的函数头文件中包含你的参数名称,而不是作为一个目的本身(尽管我完全赞成减少重复和增加简洁性),而是作为一种启发式方法您正在命名您的功能。(请注意,如果您正在使用遗留代码,您可能希望放松自己——但要记住最终目标。)

这种方法意味着您每次输入函数头时都必须停下来思考以检查自己,而不是遵循关于是否包含参数名称的黑白规则。程序员倾向于提前充电,而不是停下来思考命名之类的事情,但停下来反思在许多不同的层面上都是有价值的。

总之,力争不必须包含在报头中的参数名称; 当您不需要它们时,为了简洁和减少重复,不要费心包含它们。