我有一个同事,他坚持认为他的代码不需要注释,这是“自文档”。
我已经审阅了他的代码,虽然它比我看到的其他人编写的代码更清晰,但我仍然不同意自文档化代码与经过注释和文档化的代码一样完整和有用。
帮我理解一下他的观点。
什么是自文档代码
它真的能取代注释良好和文档化的代码吗
在某些情况下,它是否比有良好文档和注释的代码更好
是否存在代码不可能在没有注释的情况下自文档化的例子
也许这只是我自身的局限性,但我看不出这怎么能成为一种好的练习。
这并不是一个争论——请不要提出为什么注释良好并有文档记录的代码是高优先级的原因——有很多资源都表明了这一点,但它们对我的同行来说并没有说服力。我认为我需要更全面地了解他的观点,才能说服他。如果你有必要,可以提出一个新的问题,但不要在这里争论。
另外,那些反对自我记录代码的人——这主要是为了帮助我理解自我记录代码传播者的观点(即积极的方面)。
既然这是关于注释和代码的,那么让我们来看一些实际的代码。比较下面的典型代码:
float a, b, c; a=9.81; b=5; c= .5*a*(b^2);
到这个显示正在执行的操作的自文档代码:
const float gravitationalForce = 9.81;
float timeInSeconds = 5;
float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);
然后是这个文档代码,它更好地解释了为什么要这样做:
/* compute displacement with Newton's equation x = vₒt + ½at² */
const float gravitationalForce = 9.81;
float timeInSeconds = 5;
float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);
最终版本的代码作为文档,不需要注释:
float computeDisplacement(float timeInSeconds) {
const float gravitationalForce = 9.81;
float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);
return displacement;
}
下面是一个糟糕评论风格的例子:
const float a = 9.81; //gravitational force
float b = 5; //time in seconds
float c = (1/2)*a*(b^2) //multiply the time and gravity together to get displacement.
在最后一个例子中,当变量应该被描述性地命名时,就会使用注释,当我们可以清楚地看到操作是什么时,就会总结操作的结果。无论如何,我更喜欢自文档化的第二个示例,也许这就是您的朋友所说的自文档化代码。
我会说,这取决于你所做的事情的背景。对我来说,在这种情况下,自编文档的代码可能就足够了,但是详细描述所做事情(在本例中是方程)背后的方法的注释也很有用。
在顺序:
Self-documenting code is code that clearly expresses its intent to the reader.
Not entirely. Comments are always helpful for commentary on why a particular strategy was chosen. However, comments which explain what a section of code is doing are indicative of code that is insufficiently self-documenting and could use some refactoring..
Comments lie and become out of date. Code always tells is more likely to tell the truth.
I've never seen a case where the what of code couldn't be made sufficiently clear without comments; however, like I said earlier, it is sometimes necessary/helpful to include commentary on the why.
然而,需要注意的是,真正的自文档化代码需要大量的自我和团队纪律。您必须学会以声明的方式编程,并且必须非常谦虚,避免使用“聪明”的代码,而应该使用那些似乎任何人都可以编写的代码。
好的设计结构有助于指出,有些函数是通用的,有些是随机的业务逻辑,即使你没有评论说“这个函数是通用的”。
We should not forget about design and specification documentation though. Those have or at least should have much of the texts that are not necessarily needed in comments. Software often have also user manuals and other description documents, and those should be in sync with what the program does. The situation is not great if the user has to find out what the software does from the source code instead of a manual. So self documenting code still doesn't mean that the actual software has been documented.
还要考虑功能的可跟踪性。当你有了你的手册,那么你应该能够追踪到源代码的特性,并返回更好的可维护性。手册和规范与编程没有太大关系,但它们与软件工程有关。软件越大,需要的工程设计就越多。