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

时间:2011-10-25 15:15:10

标签: 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//
}

内部标题:

//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//
}

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

4 个答案:

答案 0 :(得分:25)

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

大多数文档系统(比如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. 

和这个

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. 

你明白了。 :)

答案 1 :(得分:10)

在声明中包含参数名称。

最好以尽可能紧凑的格式为其他开发人员提供尽可能多的信息。强迫他们查看注释以确定类似参数的简单内容可能会将它们从流程中移除,从而降低它们的效率,并使它们失效。

答案 2 :(得分:4)

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

void save(const std::string&);

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

所以你可以这样做:

void save(const std::string& filepath);

澄清。但这只是在有人正在寻找标题时才澄清。相反,如果你这样做:

void saveToFilepath(const std::string&);
到处都应该很清楚。当然,随着你添加更多参数,这变得更加繁琐(但是还有一个原因就是不添加太多参数;请参阅Bob Martin的清洁代码;他赞扬Nullary和一元函数,犹豫不决关于二元函数,对三元函数非常保持沉默,并且不愿意再多说这些函数。)

所以我的建议是努力没有理由将你的参数名称包含在你的函数头文件中,而不是作为一个结尾本身(尽管我只是为了减少重复和增加简洁),但作为一个启发式你如何命名你的功能。 (请注意,如果您正在使用遗留代码,您可能希望减少自己的松懈 - 但要考虑到最终目标。)

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

总之,努力不要需要在标题中包含参数名称;当你不需要它们时,不要费心包括它们,为了简洁和减少重复。

答案 3 :(得分:3)

我的经验法则是命名一切。并非每个头文件在每个函数之前都有很好的注释,因此当缺少合适的文档时,参数名称仍然是解密函数的所有内容。

在最坏的情况下,代表程序员进行一些额外的打字。除了提供的任何评论之外,它还显示了意图。从来没有人提倡过一种纯粹为了节省打字而存在的做法。在自动完成iDE的这些日子里,简单起来从未如此简单。