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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

我认为——就像你们中的许多人一样——要真正实现自文档化,代码需要显示某种形式的意图。但是我很惊讶没有人提到BDD——行为驱动开发。这个想法的一部分是,你有自动化的测试(代码)来解释你的代码的意图,这是很难明显的。

Good domain modeling 
+ good names (variabes, methods, classes) 
+ code examples (unit tests from use cases) 
= self documenting software 

其他回答

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.

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

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.

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

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

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

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

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

图。

大多数文档/注释都是为了帮助未来的代码增强者/开发人员,从而使代码可维护。 通常情况下,我们会在稍后的时间回到我们的模块来添加新功能或优化。 在那个时候,通过简单地阅读注释来理解代码要比通过大量的断点来理解代码容易得多。 此外,我宁愿花时间思考新的逻辑,而不是破译现有的。