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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

我想他可能想说的是,如果注释解释了代码的功能,那么就应该重写,以明确它的意图。这就是他所说的自文档代码。这通常意味着简单地用描述性函数名将长函数分解成逻辑上的小块。

这并不意味着代码不应该被注释。这意味着注释应该提供代码以这种方式编写的原因。

其他回答

当你阅读“自文档代码”时, 你看它在做什么, 但你不能总是猜测它为什么会以那种特定的方式运行。

有大量的非编程约束 比如业务逻辑、安全性、用户需求等。

当您进行维护时,这些背景信息变得非常重要。

只是我的一小撮盐……

如果没有注释,代码就不完全清晰,那么还有改进代码的空间。

我并不是说“不要评论不清楚的代码”。我说的是“让你的代码清晰”。

如果你最终让你的代码在某种程度上不清楚,那么使用注释来弥补。

首先,考虑下面的代码片段:

/**
 * Sets the value of foobar.
 *
 * @foobar is the new vaue of foobar.
 */
 public void setFoobar(Object foobar) {
     this.foobar = foobar;
 }

在这个例子中,每3行代码有5行注释。更糟糕的是,注释没有添加任何你在阅读代码时看不到的东西。如果你有10个这样的方法,你可能会得到“注释盲视”,没有注意到一个偏离模式的方法。

当然,更好的版本应该是:

/**
 * The serialization of the foobar object is used to synchronize the qux task.
 * The default value is unique instance, override if needed.
 */
 public void setFoobar(Object foobar) {
     this.foobar = foobar;
 }

不过,对于简单的代码,我更喜欢没有注释。意图和整体组织最好在代码之外的单独文档中解释。

对我来说,阅读需要注释的代码就像阅读我不懂的语言的文本。我看到声明,但我不明白它是做什么的,也不明白为什么——我不得不看注释。我读了一个短语,我需要查字典来理解它的意思。

编写自记录其功能的代码通常很容易。要告诉你为什么这样做注释更合适,但即使在这里代码也可以更好。如果您在抽象的每一个层次上都理解您的系统,那么您应该尝试像这样组织代码

public Result whatYouWantToDo(){
  howYouDoItStep1();
  howYouDoItStep2();
  return resultOfWhatYouHavDone;
}

方法名反映了你的意图,方法体解释了你如何实现你的目标。 无论如何,你不能从书名中看出整本书,所以你的系统的主要抽象仍然必须被记录下来,还有复杂的算法、非平凡的方法契约和工件。

If the code that your colleague produc is really self-documented - lucky you and him. If you think that your colleagues code needs comments - it needs. Just open the most non-trivial place in it, read it once and see if you understood everything or not. If the code is self-documented - then you should. If not - ask your colleague a question about it, after he gives you an answer ask why that answer was not documented in comments or code beforehand. He can claim that code is self-document for such smart person as him, but he anyway has to respect other team members - if your tasks require understanding of his code and his code does not explain to you everything you need to understand - it needs comments.

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

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.

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