15.2 Write the comments first 首先写注释

I use a different approach to writing comments, where I write the comments at the very beginning:

我使用一种不同的方法来编写注释,在开始时就写注释:

  • For a new class, I start by writing the class interface comment.
  • Next, I write interface comments and signatures for the most important public methods, but I leave the method bodies empty.
  • I iterate a bit over these comments until the basic structure feels about right.
  • At this point I write declarations and comments for the most important class instance variables in the class.
  • Finally, I fill in the bodies of the methods, adding implementation comments as needed.
  • While writing method bodies, I usually discover the need for additional methods and instance variables. For each new method I write the interface comment before the body of the method; for instance variables I fill in the comment at the same time that I write the variable declaration.

  • 对于新类,我首先编写类接口注释。
  • 接下来,我为最重要的公共方法编写接口注释和签名,但将方法主体保留为空。
  • 我对这些注释进行了迭代,直到基本结构感觉正确为止。
  • 在这一点上,我为类中最重要的类实例变量编写了声明和注释。
  • 最后,我填写方法的主体,并根据需要添加实现注释。
  • 在编写方法主体时,我通常会发现需要其他方法和实例变量。对于每个新方法,我在方法主体之前编写接口注释。例如变量,我在编写变量声明的同时填写了注释。

When the code is done, the comments are also done. There is never a backlog of unwritten comments.

代码完成后,注释也将完成。从来没有积压的书面注释。

The comments-first approach has three benefits. First, it produces better comments. If you write the comments as you are designing the class, the key design issues will be fresh in your mind, so it’s easy to record them. It’s better to write the interface comment for each method before its body, so you can focus on the method’s abstraction and interface without being distracted by its implementation. During the coding and testing process you will notice and fix problems with the comments. As a result, the comments improve over the course of development.

注释优先的方法具有三个好处。首先,它会产生更好的注释。如果您在设计课程时写注释,那么关键的设计问题将在您的脑海中浮现,因此很容易记录下来。最好在每个方法的主体之前编写接口注释,这样您就可以专注于方法的抽象和接口,而不会因其实现而分心。在编码和测试过程中,您会注意到并修复注释问题。结果,注释在开发过程中得到了改善。