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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

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

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

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.

其他回答

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

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

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

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

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

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.

This is an excellent question. It traces back to the first programming language that allowed comments, I'm sure. The code certainly should be as self-documenting as possible. Comments that point out the obvious, should be eliminated. Comments that make it easier to understand the intent, purpose, and use of a given method or section of code can be invaluable to those of us dolts that may be less familiar with the language or code in question. Structured comments that allow for the generation of API documentation are a good example. Just don't comment an IF statement that checks to see if a checkbox is checked and tell me that you're checking to see if the checkbox is checked. Restating the obvious in a comment is the worst waste keystrokes in our universe.

//For example, the above text deals with what is a useful comment

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