我有一个同事,他坚持认为他的代码不需要注释,这是“自文档”。
我已经审阅了他的代码,虽然它比我看到的其他人编写的代码更清晰,但我仍然不同意自文档化代码与经过注释和文档化的代码一样完整和有用。
帮我理解一下他的观点。
什么是自文档代码
它真的能取代注释良好和文档化的代码吗
在某些情况下,它是否比有良好文档和注释的代码更好
是否存在代码不可能在没有注释的情况下自文档化的例子
也许这只是我自身的局限性,但我看不出这怎么能成为一种好的练习。
这并不是一个争论——请不要提出为什么注释良好并有文档记录的代码是高优先级的原因——有很多资源都表明了这一点,但它们对我的同行来说并没有说服力。我认为我需要更全面地了解他的观点,才能说服他。如果你有必要,可以提出一个新的问题,但不要在这里争论。
另外,那些反对自我记录代码的人——这主要是为了帮助我理解自我记录代码传播者的观点(即积极的方面)。
在顺序:
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.
然而,需要注意的是,真正的自文档化代码需要大量的自我和团队纪律。您必须学会以声明的方式编程,并且必须非常谦虚,避免使用“聪明”的代码,而应该使用那些似乎任何人都可以编写的代码。
首先,很高兴听到您同事的代码实际上比您见过的其他代码更清晰。这意味着他可能不会用“自记录”作为懒得注释代码的借口。
自文档代码是不需要自由文本注释的代码,以便知情的读者理解它在做什么。例如,这段代码是自记录的:
print "Hello, World!"
这也是:
factorial n = product [1..n]
这也是:
from BeautifulSoup import BeautifulSoup, Tag
def replace_a_href_with_span(soup):
links = soup.findAll("a")
for link in links:
tag = Tag(soup, "span", [("class", "looksLikeLink")])
tag.contents = link.contents
link.replaceWith(tag)
现在,“知情读者”这个概念是非常主观和情境化的。如果你或其他人在遵循同事的代码方面遇到了困难,那么他最好重新评估一下他对博学读者的看法。为了调用代码自文档化,必须假定对所使用的语言和库有一定程度的熟悉。
我所见过的关于编写“自文档化代码”的最佳论据是,它避免了自由文本注释与代码编写时不一致的问题。最好的批评是,虽然代码可以描述它自己在做什么以及如何做,但它不能解释为什么某些事情会以某种方式完成。
自文档代码通常使用与代码所做的事情完全匹配的变量名,这样就很容易理解发生了什么
然而,这样的“自文档代码”永远不会取代注释。有时代码太复杂,自文档化代码是不够的,特别是在可维护性方面。
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.