这是用户在 2024-3-17 13:22 为 https://blogs.oracle.com/javamagazine/post/java-comments-reduce-technical-debt 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Reduce technical debt by valuing comments as much as code
通过像重视代码一样重视评论来减少技术债务

January 19, 2023 | 8 minute read
2023 年 1 月 19 日 | 8分钟读完
Text Size 100%:

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)。请注意,Martin 在他的《Clean Code》一书中做了这个奇怪的陈述,然后花了 15 页的篇幅列举了注释非常有用的许多实例。

uncle bob martin tweet on comment
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.
类开头的 Javadoc 注释可以替代文件级注释。如果评论描述了班级在更大项目中的角色,它们就会进一步帮助读者。

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.
对为什么需要该类的描述(如果不明显)可以帮助其他人理解该类的角色。这些注释对于在类的 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.
注释解释了代码。许多开发人员都有一种不切实际的信念,即如果代码足够清晰,他们就不需要使用注释。这就是 Bob Martin 在图 1 中所断言的。这是一个可爱的前提,但根本不成立。第一个问题是,大多数开发人员都面临着巨大的时间压力,没有时间让代码变得非常清晰,以至于不需要进一步的注释。

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.
事实上,程序员更常见的经历是看着他们六个月前编写的代码并思考“我不敢相信我写了那个!”不要欺骗自己,你可以编写如此清晰的代码,不需要任何注释就可以理解。

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.
评论强调了潜在的问题。例如,谷歌的 Java 指南要求每当 switch 中的 case 语句落入下一个 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.
同样,指南要求注意并解释空的异常 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.
虽然不是专门针对技术债务的对策,但我使用第三个标记 CURR 来表示“当前”。这是一种面包屑,告诉我在哪里停止编码。我经常添加几行注释,其中包含恢复工作时可能需要的信息。

I allow only one CURR in a codebase, so if I resume work elsewhere, I convert the existing CURR to a TODO.
我在代码库中只允许有一个 CURR,因此如果我在其他地方恢复工作,我会将现有的 CURR 转换为 TODO。

an example of excellent commenting
Figure 2. An example of excellent commenting.
图 2. 优秀评论的示例。

The Ousterhout approach to comments
Ousterhout 的评论方法

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.
John Ousterhout 的优秀著作《软件设计哲学》描述了大型代码库的最佳实践;它继承了 Martin 留下的内容,并且更加面向现实世界的情况。

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).
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.
虽然 Ousterhout 的书只有 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.
Ousterhout 的一般格言是,代码中的注释应该传达程序员心中无法准确反映在代码本身中的任何内容。

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.
这是一个很好的指导方针,直接反驳了“每条评论都是失败”的论点。真正的失败是忽略了后续编码人员可能需要的澄清和上下文信息。

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.
根据 Ousterhout 的经验,这些步骤的好处是三重的。

  • 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.
在需要评论的内容中,Ousterhout 认为最重要的是抽象(很难通过阅读实现代码来梳理出来)和对代码存在原因的解释。

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.
总之,第一次处理代码的开发人员应该能够浏览类的注释,很好地了解类的作用并理解最重要的实现方面。

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.
Java 开发人员有一个出色的工具来追求这种更深入的方法:Javadoc 注释。如果您用多种语言编写代码,您很快就会意识到其他语言的注释选项是多么微不足道。大多数语言没有任何内置的 Javadoc 对应项。

Or, as in the case of Go and a few other languages, if they have a counterpart, it’s threadbare by comparison.
或者,就像 Go 和其他一些语言一样,即使它们有对应的语言,相比之下它也是陈旧的。

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.
Javadoc 允许您将注释转换为优雅、格式良好且可用的文档。正如您从 JDK 发行版中的优秀文档中看到的那样,Java 团队以深思熟虑、认真负责的方式充分利用了该工具。

(By the way, the JVM itself is extensively commented.)
(顺便说一句,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(这是一个用 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 深入挖掘

Andrew Binstock 安德鲁·宾斯托克

Andrew Binstock (@platypusguy) is the lead developer on the Jacobin JVM project—a JVM written entirely in Go. He was formerly the editor in chief of Java Magazine, and before that he was the editor of Dr. Dobb’s Journal. Earlier, he cofounded the company behind the open source iText PDF library. He lives in Northern California with his wife, and when he’s not coding, he studies piano.
Andrew Binstock (@platypusguy) 是 Jacobin JVM 项目的首席开发人员,该项目是一个完全用 Go 编写的 JVM。他曾任 Java Magazine 的主编,此前他曾担任 Dr. Dobb's Journal 的编辑。早些时候,他与他人共同创立了开源 iText PDF 库的公司。他和妻子住在北加州,当他不编码时,他就学习钢琴。


Previous Post 上一篇文章

Curly Braces #8: REST peacefully with GraphQL and Java
大括号 #8:使用 GraphQL 和 Java 平静地休息

Eric J. Bruno | 8 min read
埃里克·J·布鲁诺 | Eric J. Bruno 8 分钟阅读

Next Post 下一篇文章


Quiz yourself: Handling side effects in Java
自测:处理 Java 中的副作用

Mikalai Zaikin | 5 min read
米卡莱·扎伊金 | 5 分钟阅读
Oracle Chatbot
Disconnected