我有一个同事,他坚持认为他的代码不需要注释,这是“自文档”。
我已经审阅了他的代码,虽然它比我看到的其他人编写的代码更清晰,但我仍然不同意自文档化代码与经过注释和文档化的代码一样完整和有用。
帮我理解一下他的观点。
什么是自文档代码
它真的能取代注释良好和文档化的代码吗
在某些情况下,它是否比有良好文档和注释的代码更好
是否存在代码不可能在没有注释的情况下自文档化的例子
也许这只是我自身的局限性,但我看不出这怎么能成为一种好的练习。
这并不是一个争论——请不要提出为什么注释良好并有文档记录的代码是高优先级的原因——有很多资源都表明了这一点,但它们对我的同行来说并没有说服力。我认为我需要更全面地了解他的观点,才能说服他。如果你有必要,可以提出一个新的问题,但不要在这里争论。
另外,那些反对自我记录代码的人——这主要是为了帮助我理解自我记录代码传播者的观点(即积极的方面)。
自文档代码是非常清晰的代码,以至于不需要注释。我举个小例子:
//iterate from 0 to 100
for(int i=0; i < 100; i++) {
println i
}
注释没什么用,因为代码很清楚。文档是一个很好的实践,但是额外的文档会给代码增加不必要的干扰。你的同事需要知道的是,不是每个人都能阅读别人的代码并了解所有的细节。
int calc(int a, int b) {
return sqrt(a*a + b*b); //pythagoras theorem
}
如果没有注释,最后一个片段将很难破译。你可以想象其他更做作的例子。
I think its a matter of the right amount of documentation, rather than all or none. If the parameters to a function are well named, you often don't have to say exactly what they are, e.g. char *CustomerName is pretty obvious. If you use assert value ranges for parameters, you don't have to document those ranges as well. IMO, documentation should cover everything which is less than obvious and hence needs some explanation, and most code needs some documentation. Personally, I'd rather see an illustrative example of how a given function works than descriptive documentation, in most cases.
为了文档而编写文档可能会浪费时间,因为文档需要维护,以便与代码库保持同步。如果没有人会从阅读中受益,那就不要写。
在顺序:
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.
然而,需要注意的是,真正的自文档化代码需要大量的自我和团队纪律。您必须学会以声明的方式编程,并且必须非常谦虚,避免使用“聪明”的代码,而应该使用那些似乎任何人都可以编写的代码。