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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

代码本身总是对代码功能的最新解释,但在我看来,它很难解释意图,这是注释最重要的方面。如果代码写得很好,我们已经知道代码的功能,我们只需要知道它到底为什么这样做!

其他回答

为什么代码之外的额外注释可能会更清晰,原因如下:

您正在查看的代码是自动生成的,因此对代码的任何编辑都可能在下次编译项目时失败 一个不太直接的实现被用来换取性能的提高(展开循环,为昂贵的计算创建查找表,等等)。

这将完全取决于团队在文档中的价值。我建议记录为什么/意图而不是如何是重要的,这并不总是在自记录代码中捕获。获取/设置没有这些是显而易见的-但计算,检索等一些为什么应该表达。

如果你来自不同的国家,你也要意识到你的团队中的差异。措辞上的差异会影响到方法的命名:

BisectionSearch

BinarySearch

二进制斩

这三种方法都是由在3个不同大洲接受过培训的开发人员提供的。只有通过阅读描述算法的注释,我们才能识别库中的重复。

自文档代码通常使用与代码所做的事情完全匹配的变量名,这样就很容易理解发生了什么

然而,这样的“自文档代码”永远不会取代注释。有时代码太复杂,自文档化代码是不够的,特别是在可维护性方面。

I once had a professor who was a firm believer in this theory In fact the best thing I ever remember him saying is "Comments are for sissies" It took all of us by surprise at first but it makes sense. However, the situation is that even though you may be able to understand what is going on in the code but someone who is less experienced that you may come behind you and not understand what is going on. This is when comments become important. I know many times that we do not believe they are important but there are very few cases where comments are unnecessary.

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

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

Self documenting code is code that is trivially easy to understand. Variable naming goes a long way to making code self documenting, but i find the best tactic is to break any complicated logic down into tiny little chunks and refactor that information into seperate methods with verbose and informative names. Then your complicated methods become simply a list of steps to be performed. The tiny private helper methods then are documented sufficiently by their own method name and the complicated methods are documented as a sequence of abstract steps to be performed. In practice this strategy cannot always be applied perfectly so comments are still very useful. Plus you should never completely abandon any tool which will help you write code that is easier to understand.