我有一个同事,他坚持认为他的代码不需要注释,这是“自文档”。

我已经审阅了他的代码,虽然它比我看到的其他人编写的代码更清晰,但我仍然不同意自文档化代码与经过注释和文档化的代码一样完整和有用。

帮我理解一下他的观点。

什么是自文档代码 它真的能取代注释良好和文档化的代码吗 在某些情况下,它是否比有良好文档和注释的代码更好 是否存在代码不可能在没有注释的情况下自文档化的例子

也许这只是我自身的局限性,但我看不出这怎么能成为一种好的练习。

这并不是一个争论——请不要提出为什么注释良好并有文档记录的代码是高优先级的原因——有很多资源都表明了这一点,但它们对我的同行来说并没有说服力。我认为我需要更全面地了解他的观点,才能说服他。如果你有必要,可以提出一个新的问题,但不要在这里争论。

另外,那些反对自我记录代码的人——这主要是为了帮助我理解自我记录代码传播者的观点(即积极的方面)。


当前回答

我认为自记录代码是注释的一个很好的替代品。如果您需要注释来解释代码是如何或为什么是这样的,那么您应该修改函数或变量名以使其更具解释性。这可能取决于编码器是否会用注释或重命名一些变量和函数并重构代码来弥补不足。

但是,它并不能真正取代您的文档,因为文档是您提供给其他人用来解释如何使用您的系统的,而不是它是如何工作的。

编辑:我(可能还有其他所有人)应该有一个数字信号处理(DSP)应用程序应该很好地注释的规定。这主要是因为DSP应用程序本质上是2 for循环,提供了数组的值和添加/乘以/等等所说的值…要更改程序,您需要更改其中一个数组中的值…需要一些评论来说明在这种情况下你在做什么;)

其他回答

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.

为了文档而编写文档可能会浪费时间,因为文档需要维护,以便与代码库保持同步。如果没有人会从阅读中受益,那就不要写。

在我工作的一家公司里,一个程序员把下面的文字粘在了她的显示器上。

“就像维护代码的人是一个知道你住在哪里的杀人狂一样,记录你的代码。”

This is an excellent question. It traces back to the first programming language that allowed comments, I'm sure. The code certainly should be as self-documenting as possible. Comments that point out the obvious, should be eliminated. Comments that make it easier to understand the intent, purpose, and use of a given method or section of code can be invaluable to those of us dolts that may be less familiar with the language or code in question. Structured comments that allow for the generation of API documentation are a good example. Just don't comment an IF statement that checks to see if a checkbox is checked and tell me that you're checking to see if the checkbox is checked. Restating the obvious in a comment is the worst waste keystrokes in our universe.

//For example, the above text deals with what is a useful comment

不管纯粹的自文档代码是否可以实现,有一些事情是人们应该做的:

Never have code that is "surprising". Ie. don't use silly macro's to redefine things etc. Don't misuse operator overloading, don't try to be smart on this. Split away code at the right point. Use proper abstractions. Instead of inlining a rolling buffer (a buffer with fixed length, with two pointers that gets items added at one end and removed at the other), use an abstraction with a proper name. Keep function complexity low. If it gets too long or complex, try to split it out into other other functions.

当实现特定的复杂算法时,添加描述算法的文档(或链接)。但在这种情况下,要努力去除不必要的复杂性,增加易读性,因为很容易犯错误。

我忘了我从哪学来的,但是:

程序中的每一条评论都像是对读者的道歉。“很抱歉,我的代码太晦涩了,你看了都看不懂。”我们只需要接受我们并不完美,但要努力做到完美,在需要的时候道歉。