博主拙见:必要的注释确实对阅读代码有很多帮助。虽然有一种思想是代码写的可以让人一眼看明白功能,但现实中,此等高人少之又少,必要的注释作为沟通高低技术层的桥梁是必须的。
以下内容英文部分完整转载自 Andrew Binstock 撰写的:Reduce technical debt by valuing comments as much as code
文中翻译来自:彩云小译
Good comments help maintainers understand your coding decisions.
好的注释可以帮助维护人员理解您的编码决策。
Comments have long occupied a distinctly secondary place in the output of developers. Comments are so secondary, and so undervalued, that in today’s code they appear infrequently except as routine copyright and licensing headers at the top of files. This is a lost opportunity because good comments that are actively maintained are one of the most effective ways of reducing technical debt—that is, they lighten the workload of future programmers who will work on the code.
长期以来,注释在开发人员的产出中一直明显处于次要地位。注释是次要的,而且被低估了,以至于在今天的代码中,除了在文件顶部作为例行版权和许可头出现之外,它们很少出现。这是一个失去的机会,因为积极维护的好注释是减少技术债务的最有效方法之一ーー也就是说,它们减轻了将来编写代码的程序员的工作量。
Because the culture of many development organizations undervalues comments, team leads (and managers) allow comments to get out of sync with the code—thereby increasing technical debt instead of reducing it.
由于许多开发组织的文化低估了注释的价值,团队领导(和管理者)允许注释与代码不同步,从而增加而不是减少了技术债务。
And because undervaluing is the rule, developers learn to blame comments rather than the culture that allows them to get out of sync with the code. This negative view is articulated by Bob Martin’s assertion that every comment represents “a failure to express yourself in code” (see Figure 1). Note that in his book Clean Code, Martin makes this curious statement and then spends 15 pages enumerating the many instances when comments are highly useful.
并且因为低估是规则,开发人员学会责备注释而不是允许他们与代码不同步的文化。Bob Martin 的断言清楚地表达了这种消极的观点,即每个注释代表“在代码中表达自己的失败”(参见图1)。请注意,在他的著作《清洁代码》(Clean Code)中,Martin 提出了这个奇怪的观点,然后用15页的篇幅列举了许多注释非常有用的实例。
Figure 1. Bob Martin has strong views about comments.
图1. Bob Martin 对注释有很强的观点。
Why write comments?
为什么要写注释?
Comments eliminate technical debt in several ways.
注释可以通过几种方式消除技术债务。
Comments explain the code’s purpose. A comment at the beginning of a file explaining what functionality is found in the code removes the need to read through all methods to gather an understanding of the file. If you’re looking for a specific file, being able to read a single sentence that describes its contents greatly speeds the search. For this reason, most coding standards urge the inclusion of just such a comment in each file.
注释解释了代码的用途。文件开头的注释解释了在代码中发现了什么功能,从而消除了通读所有方法以收集对文件的理解的需要。如果你正在寻找一个特定的文件,能够阅读描述其内容的一句话大大加快了搜索速度。出于这个原因,大多数编码标准敦促在每个文件中只包含这样的注释。
The use of keywords in file-level comments can further facilitate searching through a large codebase for specific functionality.
在文件级注释中使用关键字可以进一步促进在大型代码库中搜索特定功能。
Javadoc comments at the beginning of classes can substitute for file-level comments. If the comments describe the class’s role in the larger project, they further aid the reader. A description of why the class is needed, if it’s not obvious, helps others understand the class’s role. And these comments are an especially useful place for presenting any unusual information in the API of the class.
类开头的 Javadoc 注释可以替代文件级注释。如果注释描述了类在更大的项目中的角色,它们将进一步帮助读者。描述为什么需要这个类,如果不是很明显的话,可以帮助其他人理解这个类的角色。并且这些注释对于在类的 API 中显示任何不可预料的信息格外有用。
Comments explain the code. Many developers have the quixotic belief that if the code is clear enough, they don’t need to use comments. This is what Bob Martin is asserting in Figure 1. It is a lovely premise that does not hold—at all. The first problem is that most developers are under great time pressure and don’t have the time to make the code so utterly clear that it requires no further comment. In fact, the far more common experience programmers have is looking at code they wrote just six months earlier and thinking “I can’t believe I wrote that!” Don’t kid yourself that you can write code so clear that it requires no comments to be understood.
注释解释代码。许多开发人员有一种不切实际的想法,认为如果代码足够清晰,他们就不需要使用注释。这就是图1中 Bob Martin 所断言的。这是一个完全站不住脚的可爱前提。第一个问题是,大多数开发人员都承受着巨大的时间压力,没有时间让代码如此清晰,以至于不需要进一步的注释。事实上,程序员更常见的经验是看着他们六个月前写的代码,心想“我真不敢相信我写了那个!”不要自欺欺人地认为可以编写如此清晰的代码,以至于不需要注释就可以理解。
Another limitation of the clear-code objection is that code explains only how a thing is done, not why it is done that way, especially if there are obvious alternatives; if the why is not evident and obvious, technical debt accrues in the absence of an explanation. Note that without such explanatory comments, code can be exceedingly difficult to maintain because no one dares to touch it, which is the very definition of technical debt.
清晰代码反对的另一个限制是,代码只解释一件事是如何做的,而不解释为什么要这样做,特别是如果有明显的替代方案; 如果原因不明显和显而易见,技术债务就会在没有解释的情况下累积。请注意,如果没有这样的解释性注释,维护代码可能会非常困难,因为没有人敢碰它,这正是技术债务的定义。
Comments highlight the potential gotchas.Google’s Java guidelines, for example, require a comment anytime a case statement in a switch falls through to the next case. Likewise, the guidelines require noting and explaining an empty exception catch block, as well as all other items that are either potentially overlooked, not conventional, or a frowned-upon but occasionally necessary step.
注释强调了潜在的陷阱。例如,谷歌的 Java 准则要求在开关中的 case 语句落入下一个 case 时需要注释。同样,指导方针要求注意并解释一个空的异常 catch 块,以及所有其他可能被忽略的、非常规的、或令人不快但偶尔必要的步骤的项。
Comments provide landmarks for future work. The term self-admitted technical debt refers to the TODO and FIXME comments often encountered in codebases. On the surface, these look like detritus left behind by well-meaning programmers who were subsequently occupied with other tasks. However, an interesting study on well-maintained open source projects, “An empirical study on the removal of self-admitted technical debt,” found that 74% of such entries are removed within 180 days, most often by the developers who put them there. In other words, such comments often represent useful landmarks for future work, rather than detritus.
注释为今后的工作提供了里程碑。术语自我承认的技术债务是指在代码库中经常遇到的 TODO 和 FIXME 注释。表面上看,这些看起来像是善意的程序员留下的碎片,他们随后被其他任务所占据。然而,一项关于维护良好的开源项目的有趣研究,“一项关于去除自认技术债务的实证研究”发现,74% 的此类条目在180天内被删除,最常见的是由开发人员把它们放在那里。换句话说,这样的注释通常代表着对未来工作有用的里程碑,而不是碎片。
While not specifically a countermeasure to technical debt, I use a third marker, CURR, for “current.” This is a breadcrumb of sorts that tells me where I left off coding. I often include several lines of comments containing the information I might need when resuming work. I allow only one CURR in a codebase, so if I resume work elsewhere, I convert the existing CURR to a TODO.
虽然不是专门针对技术债务的对策,但我使用了第三个标记 CURR 来表示“当前”这是一个分类面包屑,它告诉我在哪里停止编码。我经常包含几行注释,其中包含恢复工作时可能需要的信息。我在代码库中只允许一个 CURR,所以如果我在其他地方恢复工作,我将现有的 CURR 转换为 TODO。
Figure 2.An example of excellent commenting.
图2。一个优秀注释的例子。
The Ousterhout approach to comments
奥斯特豪特的注释方法
The benefits of comments in the previous scenarios cannot be denied. They reduce technical debt, and well-maintained comments also make it easier for new team members to understand the codebase without spending hours spelunking through dead ends or posing hundreds of questions to existing staff.
在前面的场景中,注释的好处是不可否认的。它们减少了技术债务,并且良好维护的注释也使得新团队成员更容易理解代码库,而不必花费数小时深入挖掘死胡同,或者向现有员工提出数百个问题。
However, a culture of valuing comments can encourage their use for far more than remediation of technical debt.
然而,重视注释的文化可以鼓励人们使用注释,而不仅仅是为了补救技术债务。
John Ousterhout’s excellent book, “A Philosophy of Software Design,” describes best practices for large codebases; it picks up where Martin leaves off and is much more oriented towards real-world situations. Ousterhout was the designer and implementer of the Tcl language; he later cofounded Electric Cloud, a company that specialized in DevOps tools for massive codebases (that is, codebases with more than 1 million lines of code).
John Ousterhout 的优秀著作《软件设计的哲学》描述了大型代码库的最佳实践; 它继承了 Martin 中断的地方,并且更加面向现实世界的情况。Ousterhout 是 Tcl 语言的设计者和实现者; 他后来与人合作创建了 Electric Cloud,一家专门为大规模代码库(即拥有超过100万行代码的代码库)提供 DevOps 工具的公司。
While Ousterhout’s book is only 175 pages, it dedicates two full chapters to comments. The first chapter replies to the most common objections to writing and valuing comments; the second focuses on refining the quality of comments.
虽然奥斯特豪特的书只有175页,但它用了两个完整的章节来进行注释。第一章回答了对写作和注释最常见的反对意见; 第二章着重于提高注释的质量。
Ousterhout’s general dictum is that comments in code should convey whatever is in the programmer’s mind that cannot be reflected accurately in the code itself. This is an excellent guideline and one that directly countermands the contention that “every comment is a failure.” The real failure is omitting clarifying and contextual information a subsequent coder might need.
Ousterhout 的一般格言是,代码中的注释应该传达程序员心中无法在代码本身中准确反映出来的任何东西。这是一个极好的指导方针,它直接驳斥了“每条注释都是失败的”的论点真正的失败是忽略了后续编码器可能需要的澄清和上下文信息。
Comments can also help you clarify your own thinking. More than once, as I was writing comments for a piece of code, I recognized a defect in my implementation. This is much the same sensation as describing a problem to a colleague and having the solution appear as you’re explaining the problem—a common experience. In an earlier article, I described an extension of this benefit in a hybrid approach that takes elements from Ousterhout’s book.
注释也可以帮助你澄清自己的想法。不止一次,当我为一段代码编写注释时,我发现了实现中的一个缺陷。这种感觉与向同事描述一个问题,并在解释问题时找到解决方案非常相似——这是一种常见的经历。在之前的一篇文章中,我用一种混合方法描述了这种优势的扩展,该方法借鉴了 Ousterhout 的书中的一些元素。
When you create a class, consider using the following useful steps, which are a significant expansion of the use of comments:
当您创建一个类时,请考虑使用以下有用的步骤,这些步骤是注释使用的重要扩展:
- Write the class interface comment first.
- 首先编写类接口注释。
- Write the interface comments and signatures of the most important public methods, but leave the method bodies empty.
- 编写最重要的公共方法的接口注释和签名,但将方法体保留为空。
- Write comments and declarations for the most important instance variables.
- 为最重要的实例变量编写注释和声明。
- Fill in the bodies of the methods, adding implementation comments as you go along.
- 填充这些方法的主体,并在执行过程中添加实现注释。
- As you discover the need for more methods, write the comments before the body.
- 当您发现需要更多的方法时,请在主体之前编写注释。
According to Ousterhout’s experience, the benefits of these steps are threefold.
根据奥斯特豪特的经验,这些步骤的好处有三个方面。
- When the code is done, it’s properly commented and the comments are entirely up to date.
- 当代码完成时,它被正确地注释,注释完全是最新的。
- The comment-first approach enables you to focus on the abstractions rather than being distracted by the implementation.
- 注释优先的方法使您能够专注于抽象,而不是被实现分散注意力。
- The comments reveal code complexity—if a method or variable requires a long, complex comment, it probably needs to be rethought and simplified.
- 注释揭示了代码的复杂性ーー如果一个方法或变量需要一个长而复杂的注释,它可能需要重新考虑和简化。
That’s a lot of benefits!
好处多多啊!
Of the things to comment, the most important in Ousterhout’s view are abstractions (which are difficult to tease out from reading the implementation code) and an explanation of why the code exists. In sum, a developer working on your code for the first time should be able to scan the class’s comments and have a good idea of what the class does and understand the most important implementation aspects.
在需要注释的事情中,Ousterhout 认为最重要的是抽象(很难从阅读实现代码中梳理出来)和对代码存在原因的解释。总之,第一次编写代码的开发人员应该能够扫描类的注释,并且对类的功能有一个很好的了解,并且理解最重要的实现方面。
If this approach appeals to you—as it does to me—Ousterhout suggests that you use it until you’re accustomed to writing code this way. He contends, and I agree, that doing so will convert you by delivering cleaner, clearer code that is fully commented.
如果这种方法对您有吸引力ーー正如它对我的吸引力ーー Ousterhout 建议您使用它,直到您习惯以这种方式编写代码为止。他认为,我也同意,这样做可以通过提供完全注释的更清晰、更清晰的代码来转换您。
The luxury of Javadoc
Javadoc 的奢侈品
Java developers have an excellent tool for pursuing this deeper approach: Javadoc annotations. If you write code in more than one language, you’ll quickly come to realize how paltry the commenting options are in other languages. Most languages do not have any built-in counterpart to Javadoc. Or, as in the case of Go and a few other languages, if they have a counterpart, it’s threadbare by comparison.
Java 开发人员有一个非常好的工具来实现这种更深层次的方法: Javadoc 注释。如果您使用多种语言编写代码,您将很快意识到其他语言的注释选项是多么微不足道。大多数语言没有任何内置的 Javadoc 对应物。或者,就像围棋和其他一些语言一样,如果它们有对应的语言,相比之下就会显得很陈旧。
Javadoc lets you convert comments into elegant, well-formatted, and usable documentation. And as you can see from the excellent docs in the JDK distribution, the Java team has made full use of the tool in a thoughtful, conscientious discipline. (By the way, the JVM itself is extensively commented.)
Javadoc 允许您将注释转换为优雅的、格式良好的和可用的文档。从 JDK 发行版中的优秀文档中可以看出,Java 团队以一种深思熟虑、认真负责的方式充分利用了该工具。(顺便说一下,JVM 本身被广泛地注释了。)
Comments in open source projects
开源项目中的注释
A final note: If you’re contributing to an open source project, you should deeply value comments. One of the biggest obstacles prospective collaborators have when considering joining a project is the difficulty of learning the codebase—most often because it contains no comments (outside of the license header).
最后一点: 如果你正在为一个开源项目做贡献,你应该非常重视注释。未来合作者在考虑加入项目时遇到的最大障碍之一是难以学习代码库ーー通常是因为它不包含注释(在许可头之外)。
Good open source project leaders work hard at providing accessible documentation and well-commented code so that potential contributors can grok the code easily and quickly fix a small bug without excessive effort. Projects that pride themselves on good documentation and heavy commenting, such as Redis, are rewarded with good participation.
好的开源项目领导者努力提供可访问的文档和经过良好注释的代码,这样潜在的贡献者可以轻松地理解代码,并迅速修复一个小错误,而不需要付出过多的努力。那些以良好的文档和大量注释而自豪的项目,比如 Redis,得到的回报是良好的参与。
In one project I work on, Jacobin, which is a JVM written in Go, the contributors use comments extensively. Potential contributors are also provided with an additional resource: an overview of the codebase that makes it easy to understand the overall architecture of the project and how it maps to the code layout.
在我从事的一个项目 Jacobin 中,贡献者广泛地使用注释。 Jacobin 是用 Go 编写的 JVM。还为潜在的贡献者提供了一个额外的资源: 代码库的概述,这使得理解项目的整体架构以及它如何映射到代码布局变得容易。
These steps take time, but they help the project’s contributors as much as they help the project’s intended audience by forcing Jacobin’s developers to be explicit in our assumptions, clear in our thinking, and disciplined in our work.
这些步骤需要时间,但它们对项目贡献者的帮助和对项目预期受众的帮助是一样的,因为它们迫使 Jacobin 的开发人员在我们的假设中清晰明了,在我们的思维中清晰明了,在我们的工作中有条不紊。
Conclusion
结论
Poorly maintained comments are a clear source of technical debt. To avoid this problem, value comments as much as you do code. For example, when doing code reviews, pay particular attention not only to the comments around the new code but also to whether higher-level comments in the file are still correct in light of the new functionality.
维护不善的注释是技术债务的明显来源。为了避免这个问题,请像编写代码一样重视注释。例如,在进行代码审查时,不仅要特别注意围绕新代码的注释,而且要根据新功能特别注意文件中较高级别的注释是否仍然正确。
Because the JDK bundles Javadoc, you have the unique opportunity to thoroughly benefit from disciplined appreciation of comments—thereby eliminating technical debt.
由于 JDK 捆绑了 Javadoc,因此您有独特的机会从严格的注释欣赏中获益,从而消除技术债务。
Dig deeper
了解更多
- Annotations: An inside look注释: 内视
- Take notes as you code—lots of ’em! 按你的代码记笔记ーー很多笔记!
- Using comments to design classes使用注释设计类
- Ten Java coding antipatterns to avoid: Worst practices #5 through #1需要避免的十种 Java 编码反模式: 最糟糕的实践 # 5到 # 1
- Five code review antipatterns五种代码复查反模式
如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。
如本文对您有用,捐赠和留言 将是对我最好的支持~(捐赠可转为站内积分)
如愿意,请向朋友推荐本站,谢谢。
尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。