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

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

帮我理解一下他的观点。

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

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

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

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


当前回答

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

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

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

其他回答

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

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.

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

您可能希望向您的同事指出的一件事是,无论他的代码是如何自我记录的,如果考虑并放弃了其他替代方法,那么该信息将丢失,除非他用该信息注释代码。有时,了解考虑了替代方案以及为什么不选择它同样重要,并且代码注释最有可能随着时间的推移而幸存下来。

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

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

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

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

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.

这里的输入似乎非常复杂:)

我使用伪代码编程过程进行新的开发,这实际上使我的代码自文档化。我只在写新代码时才开始写伪代码,然后在上面扩展。我不是说这是最佳实践或类似的东西,我只是强调一个我认为有用的技巧,如果你知道你的代码需要大量的文档,如果它要交给第三方,审查者等等……它偶尔也会在我还没写一行代码的时候就给我指出一些问题。

' check database is available
  ' if it is then allow the procedure
  ' if it isnt roll back and tidy up 
' move onto something else

变成了;

' check database is available
  if checkDBStateResult(currentDB) = Open then 
     ' if it is then allow the procedure
          proc.Ok = True 
  else
     ' if it isnt roll back
          proc.Ok = False
          CleanUp()
  end if