我有一个同事,他坚持认为他的代码不需要注释,这是“自文档”。
我已经审阅了他的代码,虽然它比我看到的其他人编写的代码更清晰,但我仍然不同意自文档化代码与经过注释和文档化的代码一样完整和有用。
帮我理解一下他的观点。
什么是自文档代码
它真的能取代注释良好和文档化的代码吗
在某些情况下,它是否比有良好文档和注释的代码更好
是否存在代码不可能在没有注释的情况下自文档化的例子
也许这只是我自身的局限性,但我看不出这怎么能成为一种好的练习。
这并不是一个争论——请不要提出为什么注释良好并有文档记录的代码是高优先级的原因——有很多资源都表明了这一点,但它们对我的同行来说并没有说服力。我认为我需要更全面地了解他的观点,才能说服他。如果你有必要,可以提出一个新的问题,但不要在这里争论。
另外,那些反对自我记录代码的人——这主要是为了帮助我理解自我记录代码传播者的观点(即积极的方面)。
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.
为了文档而编写文档可能会浪费时间,因为文档需要维护,以便与代码库保持同步。如果没有人会从阅读中受益,那就不要写。
自文档代码是一个很容易解决的问题,随着时间的推移,代码、注释和文档会出现分歧。编写清晰的代码也是一个约束因素(如果你对自己有那么严格的话)。
对我来说,以下是我努力遵循的规则:
Code should be as easy and clear to
read as possible.
Comments should give reasons for
design decisions I took, like: why
do I use this algorithm, or
limitations the code has, like: does
not work when ... (this should be
handled in a contract/assertion in
the code) (usually within the function/procedure).
Documentation should list usage
(calling converntions), side
effects, possible return values. It
can be extracted from code using
tools like jDoc or xmlDoc. It
therefore usually is outside the
function/procedure, but close to the
code it describes.
这意味着所有三种记录代码的方法都很接近,因此更有可能在代码更改时被更改,但它们所表达的内容并不重叠。
自我记录代码是“DRY”(不要重复自己)的一个很好的例子。不要在注释中重复代码本身中的信息。
与其解释变量的用途,不如重命名变量。
与其解释一个简短的代码片段做什么,不如将其提取到一个方法中并给它一个描述性的名称(可能是注释文本的缩短版本)。
与其解释一个复杂的测试做什么,不如把它也提取到一个方法中,并给它起个好名字。
Etc.
在此之后,您将得到不需要太多解释的代码,它可以自行解释,因此您应该删除代码中只是重复信息的注释。
这并不意味着你完全没有注释,有一些信息你不能放入代码中,比如关于意图的信息(“为什么”)。在理想的情况下,代码和注释相互补充,每个注释都增加了独特的解释价值,而不会重复另一个注释中的信息。
不管纯粹的自文档代码是否可以实现,有一些事情是人们应该做的:
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.
当实现特定的复杂算法时,添加描述算法的文档(或链接)。但在这种情况下,要努力去除不必要的复杂性,增加易读性,因为很容易犯错误。