Principle

  1. You must precede every exported class, interface, constructor, method, and field declaration with a doc comment.
  2. If a class is serializable, you should also document its serialized form (Item 75).
  3. To write maintainable code, you should also write doc comments for most unexported classes, interfaces, constructors, methods, and fields.
  4. What comment to doc

    The doc comment for a method should describe succinctly the contract between the method and its client. With the exception of methods in classes designed for inheritance (Item 17), the contract should say what the method does rather than how it does its job.

    • Happypath

    The doc comment should enumerate all of the method's preconditions, which are the things that have to be true in order for a client to invoke it, and its postconditions , which are the things that will be true after the invocation has completed successfully.

    • Exception path

    Typically, preconditions are described implicitly by the @throws tags for unchecked exceptions; each unchecked exception corresponds to a precondition violation. Also, preconditions can be specified along with the affected parameters in their @param tags.

    • Side effects

    An observable change in the state of the system that is not obviously required in order to achieve the postcondition. For example, if a method starts a background thread, the documentation should make note of it.

    • Thread safety

    Describe the thread safety of a class or method, as discussed in Item 70.

  5. Tag description
    • @param - a noun phrase describing the value represented by parameter.
    • @return - a noun phrase describing the value represented by return value.
    • @throws - consist of the word "if", followed by a clause describing the conditions under which the exception is thrown. Occasionally, arithmetic expressions are used in place of noun phrases.
    • {@code} - it causes the code fragment to be rendered in code font, and it suppresses processing of HTML markup and nested Javadoc tags in the code fragment.

      precede the multiline code example with the characters <pre>{@code and follow it with the characters }</pre>.

    /**

    * Returns the element at the specified position in this list.

    *

    * <p>This method is <i>not</i> guaranteed to run in constant

    * time. In some implementations it may run in time proportional

    * to the element position.

    *

    * @param index index of element to return; must be

    * non-negative and less than the size of this list

    * @return the element at the specified position in this list

    * @throws IndexOutOfBoundsException if the index is out of range

    * ({@code index < 0 || index >= this.size()})

    */

    E get(int index);

    • Use the word "this" always to refers to the object on which the method is invoked when it is used in the doc comment for an instance method.
    • {@literal} - suppress processing of HTML markup and nested Javadoc tags. Unlike {@Code} tag it doesn't render the test in code font.

    * The triangle inequality is {@literal |x + y| < |x| + |y|}.

    produces the documentation: "The triangle inequality is |x + y| < |x| + |y|."

  6. Doc comments should be readable in both the source code and in the generated documentation. If you can't achieve both, generated documentation readability trumps source code readability.
  7. No two members or constructors in a class or interface should have the same summary description.
  8. If the intended summary description contains a period , because the period can prematurely terminate the description.

    /**

    * A college degree, such as B.S., {@literal M.S.} or Ph.D.

    * College is a fountain of knowledge where many go to drink.

    */

    public class Degree { ... }

9.  For methods and constructors, the summary description should be a full verb phrase (including any object) describing the action performed by the method.

• ArrayList(int initialCapacity) —Constructs an empty list with the specified initial capacity.

• Collection.size()—Returns the number of elements in this collection.

10.  For classes, interfaces, and fields, the summary description should be a noun phrase describing the thing represented by an instance of the class or interface or by the field itself.

• TimerTask—A task that can be scheduled for one-time or repeated execution by a Timer.

• Math.PI—The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

11.  When documenting a generic type or method, be sure to document all type parameters:

/**

* An object that maps keys to values. A map cannot contain

* duplicate keys; each key can map to at most one value.

*

* (Remainder omitted)

*

* @param <K> the type of keys maintained by this map

* @param <V> the type of mapped values

*/

public interface Map<K, V> {

... // Remainder omitted

}

12.  When documenting an enum type, be sure to document the constants as well as the type and any public methods.

/**

* An instrument section of a symphony orchestra.

*/

public enum OrchestraSection {

/** Woodwinds, such as flute, clarinet, and oboe. */

WOODWIND,

/** Brass instruments, such as french horn and trumpet. */

BRASS,

/** Percussion instruments, such as timpani and cymbals */

PERCUSSION,

/** Stringed instruments, such as violin and cello. */

STRING;

}

13.  When documenting an annotation type, be sure to document any members as well as the type itself.

/**

* Indicates that the annotated method is a test method that

* must throw the designated exception to succeed.

*/

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface ExceptionTest {

/**

* The exception that the annotated test method must throw

* in order to pass. (The test is permitted to throw any

* subtype of the type described by this class object.)

*/

Class<? extends Exception> value();

}

14.  If a class is serializable, you should document its serialized form, as described in Item 75.

15.  Javadoc has the ability to "inherit" method comments. If an API element does not have a doc comment, Javadoc searches for the most specific applicable doc comment, giving preference to interfaces over superclasses. You can also inherit parts of doc comments from super types using the {@inheritDoc} tag.

16.  For complex APIs consisting of multiple interrelated classes, it is often necessary to supplement the documentation comments with an external document describing the overall architecture of the API. If such a document exists, the relevant class or package documentation comments should include a link to it.

Summary

Documentation comments are the best, most effective way to document your API. Their use should be considered mandatory for all exported API elements. Adopt a consistent style that adheres to standard conventions. Remember that arbitrary HTML is permissible within documentation comments and that HTML meta characters must be escaped.

Effective Java 44 Write doc comments for all exposed API elements的更多相关文章

  1. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  2. 《Effective Java》读书笔记 - 7.方法

    Chapter 7 Methods Item 38: Check parameters for validity 直接举例吧: /** * ...其他的被我省略了 * @throws Arithmet ...

  3. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  4. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  5. How to Write Doc Comments for the Javadoc Tool

    http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describe ...

  6. Effective Java 第三版——44. 优先使用标准的函数式接口

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. 如何写Java文档注释(Java Doc Comments)

    本文翻译自How to Write Doc Comments for the Javadoc Tool,但是精简了一些私以为不重要的东西 本文不讨论如何使用javadoc工具自动生成文档的方法,而是主 ...

  8. Effective java笔记(六),方法

    38.检查参数的有效性 绝大多数方法和构造器对于传递给它们的参数值都会有限制.如,对象引用不能为null,数组索引有范围限制等.应该在文档中指明所有这些限制,并在方法的开头处检查参数,以强制施加这些限 ...

  9. [Effective Java]第八章 通用程序设计

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

随机推荐

  1. Redis设计与实现-内部数据结构篇

    题记:这本书是2015年11月份开始读的,大约花了一个多月的时间通读了一遍,最近由于需要对redis做一些深入的了解,因此又花了两个多月仔细精读了一遍,由于本书设计的内容较多,且每部分的内容都比较细致 ...

  2. 点餐APP 冲刺三总结

    一转眼所有的冲刺都完成了,而今次的冲刺主要是完善数据库,而我们 也成功地实现了,虽然过程很艰辛,但是我们每一个人都学习到了很多新 知识,这是最好的收获.因为今学期没有软件工程的课程,所以大家都是 利用 ...

  3. czxt

    实验三 进程调度模拟程序 1.    目的和要求 1.1.           实验目的 用高级语言完成一个进程调度程序,以加深对进程的概念及进程调度算法的理解. 1.2.           实验要 ...

  4. .Net 自定义应用程序配置

    .Net 自定义应用程序配置 引言 几乎所有的应用程序都离不开配置,有时候我们会将配置信息存在数据库中(例如大家可能常会见到名为Config这样的表):更多时候,我们会将配置写在Web.config或 ...

  5. 【原创】Silverlight客户端发起WebRequest请求分析

    Silverlight网站部署后,客户端浏览器访问的时候会 下载 网站的xap文件包等信息,把程序代码放到本地执行,因为本地机器上安装了silverlight运行库. 所以如果silverlight前 ...

  6. 几种web字体格式

    目前,文字信息仍是网站最主要的内容,随着CSS3技术的不断成熟,Web字体逐渐成为话题,这项让未来Web更加丰富多彩的技术拥有多种实现方案,其中之一是通过@font-face属性在网页中嵌入自定义字体 ...

  7. [转载]Ubuntu14.04 LTS更新源

    不同的网络状况连接以下源的速度不同, 建议在添加前手动验证以下源的连接速度(ping下就行),选择最快的源可以节省大批下载时间. 首先备份源列表: sudo cp /etc/apt/sources.l ...

  8. ActiveReports 报表应用教程 (5)---解密电子商务领域首张电子发票的诞生(套打报表)

    6月27日京东商城发布了中国电子商务领域首张电子发票,同时宣布相关系统正式上线,这标志着中国电子商务的步伐又向前迈出了重要的一步.目前“电子发票”覆盖的服务范围是在北京地区购买图书.音像商品的个人消费 ...

  9. mysql select语句解析

    select语句用于从一个或多个数据表选出特定行.特定列的交集 最简单的select语句的语法格式如下: select column1,column2 ........      (列) from 数 ...

  10. [PHP] 自动加载的实现

    基于psr的规范,使用命名空间和spl_autoload_register()来实现自动加载 文件结构: |--Api |--Account.php |--User.php|--Service |-- ...