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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

自我记录代码是愚蠢的。任何在几周、几个月或几年之后不得不重新访问代码的人都知道这一点(对我来说是几天)。(也许推广这个想法的人还很幼稚!?! ! !)

使用有意义的、描述性的数据名称,聪明地分解代码,并给自己留下提示,告诉自己为什么要这么做,这样你的生活就会更丰富、更充实。

尽管……我确实读过一句比尔·盖茨说过的话:“代码就是文档。”

图。

其他回答

“自文档化”代码背后的思想是,代码中的实际程序逻辑非常清楚,不仅可以向阅读代码的人解释代码在做什么,还可以向他们解释为什么要这样做。

在我看来,真正的自文档代码的想法是一个神话。代码可以告诉您正在发生的事情背后的逻辑,但它不能解释为什么要以某种方式完成,特别是如果有不止一种方法来解决问题。仅仅因为这个原因,它永远不能取代注释良好的代码。

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.

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

在顺序:

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.

然而,需要注意的是,真正的自文档化代码需要大量的自我和团队纪律。您必须学会以声明的方式编程,并且必须非常谦虚,避免使用“聪明”的代码,而应该使用那些似乎任何人都可以编写的代码。

以下是我对你的问题的最佳回答。

自文档代码是用类、方法、函数和变量名称清晰编写的代码,这些名称使其意图和函数易于理解。如果做得好,它就是文档。

它可以取代注释和文档完善的代码,但我很少见到它。很多时候,程序员认为他们已经足够好了,但是打倒他们的最好方法是开始问问题。如果他们不得不开始解释太多,那么他们的代码就不够清晰。您不应该阅读代码来了解它的功能。

在某些情况下,这样做会更好。如果代码又小又简单,那么添加文档可能会把事情弄得乱七八糟。

包含算法的代码应该包含注释。大多数时候,即使是最初的程序员也不记得几个月前他们在写一个长函数时到底在想什么。