## Chapter 8. Methods(方法)
### Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
If an API is to be usable, it must be documented. Traditionally, API documentation was generated manually, and keeping it in sync with code was a chore. The Java programming environment eases this task with the Javadoc utility. Javadoc generates API documentation automatically from source code with specially formatted documentation comments, more commonly known as doc comments.
如果 API 要可用,就必須對其進行文檔化。傳統上,API 文檔是手工生成的,保持與代碼的同步是一件苦差事。Java 編程環境使用 Javadoc 實用程序簡化了這一任務。Javadoc 使用特殊格式的文檔注釋(通常稱為文檔注釋)從源代碼自動生成 API 文檔。
While the doc comment conventions are not officially part of the language, they constitute a de facto API that every Java programmer should know. These conventions are described in the How to Write Doc Comments web page [Javadoc-guide]. While this page has not been updated since Java 4 was released, it is still an invaluable resource. One important doc tag was added in Java 9, {@index}; one in Java 8, {@implSpec}; and two in Java 5, {@literal} and {@code}. These tags are missing from the aforementioned web page, but are discussed in this item.
雖然文檔注釋約定不是正式語言的一部分,但它們實際上構成了每個 Java 程序員都應該知道的 API。這些約定在如何編寫文檔注釋的 web 頁面 [Javadoc-guide] 中進行了描述。雖然自 Java 4 發布以來這個頁面沒有更新,但它仍然是一個非常寶貴的資源。在 Java 9 中添加了一個重要的文檔標簽,`{@index}`;Java 8 有一個重要標簽,`{@implSpec}`;Java 5 中有兩個重要標簽,`{@literal}` 和 `{@code}`。上述 web 頁面中缺少這些標簽,但將在本項目中討論。
**To document your API properly, you must precede every exported class, interface, constructor, method, and field declaration with a doc comment.** If a class is serializable, you should also document its serialized form (Item 87). In the absence of a doc comment, the best that Javadoc can do is to reproduce the declaration as the sole documentation for the affected API element. It is frustrating and error-prone to use an API with missing documentation comments. Public classes should not use default constructors because there is no way to provide doc comments for them. To write maintainable code, you should also write doc comments for most unexported classes, interfaces, constructors, methods, and fields, though these comments needn’t be as thorough as those for exported API elements.
**要正確地編寫 API 文檔,必須在每個公開的類、接口、構造函數、方法和字段聲明之前加上文檔注釋。** 如果一個類是可序列化的,還應該記錄它的序列化形式([Item-87](/Chapter-12/Chapter-12-Item-87-Consider-using-a-custom-serialized-form.md))。在缺少文檔注釋的情況下,Javadoc 所能做的最好的事情就是重新生成該聲明,作為受影響的 API 元素的唯一文檔。使用缺少文檔注釋的 API 是令人沮喪和容易出錯的。公共類不應該使用默認構造函數,因為無法為它們提供文檔注釋。要編寫可維護的代碼,還應該為大多數未公開的類、接口、構造函數、方法和字段編寫文檔注釋,盡管這些注釋不需要像公開 API 元素那樣完整。
**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 19), the contract should say what the method does rather than how it does its job. 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. 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.
**方法的文檔注釋應該簡潔地描述方法與其客戶端之間的約定。** 除了為繼承而設計的類中的方法([Item-19](/Chapter-4/Chapter-4-Item-19-Design-and-document-for-inheritance-or-else-prohibit-it.md)),約定應該說明方法做什么,而不是它如何做它的工作。文檔注釋應該列舉方法的所有前置條件(這些條件必須為真,以便客戶端調用它們)和后置條件(這些條件是在調用成功完成后才為真)。通常,對于 unchecked 的異常,前置條件由 `@throw` 標記隱式地描述;每個 unchecked 異常對應于一個先決條件反例。此外,可以在前置條件及其 `@param` 標記中指定受影響的參數。
In addition to preconditions and postconditions, methods should document any side effects. A side effect is 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.
除了前置條件和后置條件外,方法還應該文檔中描述產生的任何副作用。副作用是系統狀態的一個可觀察到的變化,它不是實現后置條件所明顯需要的。例如,如果一個方法啟動了一個后臺線程,文檔應該說明。
To describe a method’s contract fully, the doc comment should have an @param tag for every parameter, an @return tag unless the method has a void return type, and an @throws tag for every exception thrown by the method, whether checked or unchecked (Item 74). If the text in the @return tag would be identical to the description of the method, it may be permissible to omit it, depending on the coding standards you are following.
要完整地描述方法的約定,文檔注釋應該為每個參數設置一個 `@param` 標記和一個 `@return` 標記(除非方法返回類型是 void),以及一個 `@throw` 標記(對于方法拋出的每個異常,無論 checked 或 unchecked)([Item-74](/Chapter-10/Chapter-10-Item-74-Document-all-exceptions-thrown-by-each-method.md)。如果 `@return` 標記中的文本與方法的描述相同,則可以忽略它,這取決于你所遵循的標準。
By convention, the text following an @param tag or @return tag should be a noun phrase describing the value represented by the parameter or return value. Rarely, arithmetic expressions are used in place of noun phrases; see BigInteger for examples. The text following an @throws tag should consist of the word “if,” followed by a clause describing the conditions under which the exception is thrown. By convention, the phrase or clause following an @param, @return, or @throws tag is not terminated by a period. All of these conventions are illustrated by the following doc comment:
按照慣例,`@param` 標記或 `@return` 標記后面的文本應該是一個名詞短語,描述參數或返回值所表示的值。算術表達式很少用來代替名詞短語;有關示例,請參見 BigInteger。`@throw` 標記后面的文本應該包含單詞「if」,后面跟著一個描述拋出異常的條件的子句。按照慣例,`@param`、`@return` 或 `@throw` 標記后面的短語或子句不以句號結束。以下的文檔注釋展示了所有這些約定:
```
/**
* 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);
```
Notice the use of HTML tags in this doc comment (<p> and <i>). The Javadoc utility translates doc comments into HTML, and arbitrary HTML elements in doc comments end up in the resulting HTML document. Occasionally, programmers go so far as to embed HTML tables in their doc comments, although this is rare.
注意,在這個文檔注釋中使用 HTML 標簽(`<p>` 和 `<i>`)。Javadoc 實用程序將文檔注釋轉換為 HTML,文檔注釋中的任意 HTML 元素最終會出現在生成的 HTML 文檔中。有時候,程序員甚至會在他們的文檔注釋中嵌入 HTML 表,盡管這種情況很少見。
Also notice the use of the Javadoc {@code} tag around the code fragment in the @throws clause. This tag serves two purposes: 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. The latter property is what allows us to use the less-than sign (<) in the code fragment even though it’s an HTML metacharacter. To include a multiline code example in a doc comment, use a Javadoc {@code} tag wrapped inside an HTML <pre> tag. In other words, precede the code example with the characters <pre>{@code and follow it with }</pre>. This preserves line breaks in the code, and eliminates the need to escape HTML metacharacters, but not the at sign (@), which must be escaped if the code sample uses annotations.
還要注意在 `@throw` 子句中的代碼片段周圍使用 Javadoc 的 `{@code}` 標記。這個標記有兩個目的:它使代碼片段以代碼字體呈現,并且它抑制了代碼片段中 HTML 標記和嵌套 Javadoc 標記的處理。后一個屬性允許我們在代碼片段中使用小于號 `(<)`,即使它是一個 HTML 元字符。要在文檔注釋中包含多行代碼,請將其包裝在 `<pre>` 標簽中。換句話說,在代碼示例之前加上字符 `<pre>{@code}</pre>`。這保留了代碼中的換行符,并消除了轉義 HTML 元字符的需要,但不需要轉義 at 符號 `(@)`,如果代碼示例使用注釋,則必須轉義 at 符號 `(@)`。
Finally, notice the use of the words “this list” in the doc comment. By convention, the word “this” refers to the object on which a method is invoked when it is used in the doc comment for an instance method.
最后,請注意文檔注釋中使用的單詞「this list」。按照慣例,「this」指的是調用實例方法的對象。
As mentioned in Item 15, when you design a class for inheritance, you must document its self-use patterns, so programmers know the semantics of overriding its methods. These self-use patterns should be documented using the @implSpec tag, added in Java 8. Recall that ordinary doc comments describe the contract between a method and its client; @implSpec comments, by contrast, describe the contract between a method and its subclass, allowing subclasses to rely on implementation behavior if they inherit the method or call it via super. Here's how it looks in practice:
正如 [Item-15](/Chapter-4/Chapter-4-Item-15-Minimize-the-accessibility-of-classes-and-members.md) 中提到的,當你為繼承設計一個類時,你必須記錄它的自用模式,以便程序員知道覆蓋它的方法的語義。這些自用模式應該使用在 Java 8 中添加的 `@implSpec` 標記來記錄。回想一下,普通的文檔注釋描述了方法與其客戶機之間的約定;相反,`@implSpec` 注釋描述了方法與其子類之間的約定,允許子類依賴于實現行為(如果它們繼承了方法或通過 super 調用方法)。下面是它在實際使用時的樣子:
```
/**
* Returns true if this collection is empty.
**
@implSpec
* This implementation returns {@code this.size() == 0}.
**
@return true if this collection is empty
*/
public boolean isEmpty() { ... }
```
As of Java 9, the Javadoc utility still ignores the @implSpec tag unless you pass the command line switch -tag "implSpec: a :Implementation Requirements:". Hopefully this will be remedied in a subsequent release.
從 Java 9 開始,Javadoc 實用程序仍然忽略 `@implSpec` 標記,除非你通過命令行開關 `-tag "implSpec: a :Implementation Requirements:"`。希望在后續的版本中可以糾正這個錯誤。
Don’t forget that you must take special action to generate documentation that contains HTML metacharacters, such as the less-than sign (<), the greater-than sign (>), and the ampersand (&). The best way to get these characters into documentation is to surround them with the {@literal} tag, which suppress processing of HTML markup and nested Javadoc tags. It is like the {@code} tag, except that it doesn’t render the text in code font. For example, this Javadoc fragment:
不要忘記,你必須采取特殊的操作來生成包含 HTML 元字符的文檔,比如小于號 `(<)`、大于號 `(>)`、與號 `(&)`。將這些字符放到文檔中最好的方法是用 `{@literal}` 標記包圍它們,這將抑制 HTML 標記和嵌套 Javadoc 標記的處理。它類似于 `{@code}` 標記,只是它不以代碼字體呈現文本。例如,這個 Javadoc 片段:
```
* A geometric series converges if {@literal |r| < 1}.
```
generates the documentation: “A geometric series converges if |r| < 1.” The {@literal} tag could have been placed around just the less-than sign rather than the entire inequality with the same resulting documentation, but the doc comment would have been less readable in the source code. This illustrates the general principle that **doc comments should be readable both in the source code and in the generated documentation.** If you can’t achieve both, the readability of the generated documentation trumps that of the source code.
生成文檔:「如果 |r| < 1,則幾何級數收斂。」`{@literal}` 標簽可以放在小于號周圍,而不是整個不等式周圍,得到的文檔是相同的,但是文檔注釋在源代碼中可讀性會更差。這說明了 **一條原則,文檔注釋應該在源代碼和生成的文檔中都具備可讀性。** 如果不能同時實現這兩個目標,要保證生成的文檔的可讀性超過源代碼的可讀性。
The first “sentence” of each doc comment (as defined below) becomes the summary description of the element to which the comment pertains. For example, the summary description in the doc comment on page 255 is “Returns the element at the specified position in this list.” The summary description must stand on its own to describe the functionality of the element it summarizes. To avoid confusion, **no two members or constructors in a class or interface should have the same summary description.** Pay particular attention to overloadings, for which it is often natural to use the same first sentence (but unacceptable in doc comments).
每個文檔注釋的第一個「句子」(定義如下)成為注釋所屬元素的摘要描述。例如,255 頁文檔注釋中的摘要描述是「返回列表中指定位置的元素」。摘要描述必須獨立地描述它總結的元素的功能。為了避免混淆,**類或接口中的任何兩個成員或構造函數都不應該具有相同的摘要描述。** 特別注意重載,對于重載,使用相同的摘要描述是很正常的(但在文檔注釋中是不可接受的)。
Be careful if the intended summary description contains a period, because the period can prematurely terminate the description. For example, a doc comment that begins with the phrase “A college degree, such as B.S., M.S. or Ph.D.” will result in the summary description “A college degree, such as B.S., M.S.” The problem is that the summary description ends at the first period that is followed by a space, tab, or line terminator (or at the first block tag) [Javadoc-ref]. Here, the second period in the abbreviation “M.S.” is followed by a space. The best solution is to surround the offending period and any associated text with an {@literal} tag, so the period is no longer followed by a space in the source code:
如果預期的摘要描述包含句點,請小心,因為句點可能會提前終止描述。例如,以「A college degree, such as B.S., M.S. or Ph.D.」開頭的文檔注釋,會產生這樣的概要描述「A college degree, such as B.S., M.S.」,問題在于,摘要描述在第一個句點結束,然后是空格、制表符或行結束符(或第一個塊標記)[Javadoc-ref]。在這種情況下,縮寫「M.S.」中的第二個句點就要接著用一個空格。最好的解決方案是用 `{@literal}` 標記來包圍不當的句點和任何相關的文本,這樣源代碼中的句點后面就不會有空格了:
```
/**
* A college degree, such as B.S., {@literal M.S.} or Ph.D.
*/
public class Degree { ... }
```
It is a bit misleading to say that the summary description is the first sentence in a doc comment. Convention dictates that it should seldom be a complete sentence. For methods and constructors, the summary description should be a verb phrase (including any object) describing the action performed by the method. For example:
將摘要描述說成是是文檔注釋中的第一句話有點誤導人。按照慣例,它通常不是一個完整的句子。對于方法和構造函數,摘要描述應該是一個動詞短語(包括任何對象),描述方法執行的動作。例如:
- ArrayList(int initialCapacity)—Constructs an empty list with the specified initial capacity.
構造具有指定初始容量的空 List。
- Collection.size()—Returns the number of elements in this collection.
返回此集合中的元素數量。
As shown in these examples, use the third person declarative tense (“returns the number”) rather than the second person imperative (“return the number”).
如這些例子所示,應使用第三人稱陳述句時態「returns the number」而不是第二人稱祈使句「return the number」。
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. For example:
對于類、接口和字段,摘要描述應該是一個名詞短語,描述由類或接口的實例或字段本身表示的事物。例如:
- Instant—An instantaneous point on the time-line.
時間線上的瞬時點。
- Math.PI—The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.
這個 double 類型的值比任何其它值的都更接近于圓周率(圓周長與直徑之比)。
In Java 9, a client-side index was added to the HTML generated by Javadoc. This index, which eases the task of navigating large API documentation sets, takes the form of a search box in the upper-right corner of the page. When you type into the box, you get a drop-down menu of matching pages. API elements, such as classes, methods, and fields, are indexed automatically. Occasionally you may wish to index additional terms that are important to your API. The {@index} tag was added for this purpose. Indexing a term that appears in a doc comment is as simple as wrapping it in this tag, as shown in this fragment:
在 Java 9 中,客戶端索引被添加到 Javadoc 生成的 HTML 中。這個索引以頁面右上角的搜索框的形式出現,它簡化了導航大型 API 文檔集的任務。當你在框中鍵入時,你將得到一個匹配頁面的下拉菜單。API 元素(如類、方法和字段)是自動索引的。有時,你可能希望索引 API 中很重要的術語。為此添加了 `{@index}` 標記。對文檔注釋中出現的術語進行索引,就像將其包裝在這個標簽中一樣簡單,如下面的片段所示:
```
* This method complies with the {@index IEEE 754} standard.
```
Generics, enums, and annotations require special care in doc comments. **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> { ... }
```
**When documenting an enum type, be sure to document the constants** as well as the type and any public methods. Note that you can put an entire doc comment on one line if it’s short:
**編寫枚舉類型的文檔時,一定要說明常量** 以及類型、任何公共方法。注意,如果文檔很短,你可以把整個文檔注釋放在一行:
```
/**
* 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;
}
```
**When documenting an annotation type, be sure to document any Members** as well as the type itself. Document members with noun phrases, as if they were fields. For the summary description of the type, use a verb phrase that says what it means when a program element has an annotation of this type:
**為注釋類型的文檔時,請確保說明全部成員** 以及類型本身。用名詞短語描述成員,就當它們是字段一樣。對于類型的摘要描述,請使用動詞短語,它表示當程序元素具有此類注解時的含義:
```
/**
* Indicates that the annotated method is a test method that
* must throw the designated exception to pass.
*/
@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 Throwable> value();
}
```
Package-level doc comments should be placed in a file named package-info.java. In addition to these comments, package-info.java must contain a package declaration and may contain annotations on this declaration. Similarly, if you elect to use the module system (Item 15), module-level comments should be placed in the module-info.java file.
包級別的文檔注釋應該放在名為 package info.java 的文件中。除了這些注釋之外,package info.java 必須包含一個包聲明,并且可能包含關于這個聲明的注釋。類似地,如果你選擇使用模塊系統([Item-15](/Chapter-4/Chapter-4-Item-15-Minimize-the-accessibility-of-classes-and-members.md)),模塊級別的注釋應該放在 module-info.java 文件中。
Two aspects of APIs that are often neglected in documentation are threadsafety and serializability. **Whether or not a class or static method is threadsafe, you should document its thread-safety** level, as described in Item 82. If a class is serializable, you should document its serialized form, as described in Item 87.
在文檔中經常忽略的 API 的兩個方面是線程安全性和可序列化性。**無論類或靜態方法是否線程安全,你都應該說明它的線程安全級別**,如 [Item-82](/Chapter-11/Chapter-11-Item-82-Document-thread-safety.md) 所述。如果一個類是可序列化的,你應該說明它的序列化形式,如 [Item-87](/Chapter-12/Chapter-12-Item-87-Consider-using-a-custom-serialized-form.md) 中所述。
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. The details of the search algorithm can be found in The Javadoc Reference Guide [Javadoc-ref]. You can also inherit parts of doc comments from supertypes using the {@inheritDoc} tag. This means, among other things, that classes can reuse doc comments from interfaces they implement, rather than copying these comments. This facility has the potential to reduce the burden of maintaining multiple sets of nearly identical doc comments, but it is tricky to use and has some limitations. The details are beyond the scope of this book.
Javadoc 具有「繼承」方法注釋的能力。如果 API 元素沒有文檔注釋,Javadoc 將搜索最適用的文檔注釋,優先選擇接口而不是超類。搜索算法的詳細信息可以在《The Javadoc Reference Guide》 [Javadoc-ref] 中找到。你還可以使用 `{@inheritDoc}` 標記從超類型繼承部分文檔注釋。這意味著類可以復用它們實現的接口中的文檔注釋,而不是復制這些注釋。這個工具有能力減少維護多個幾乎相同的文檔注釋集的負擔,但是它使用起來很棘手,并且有一些限制。這些細節超出了這本書的范圍。
One caveat should be added concerning documentation comments. While it is necessary to provide documentation comments for all exported API elements, it is not always sufficient. 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.
關于文檔注釋,有一點需要特別注意。雖然有必要為所有公開的 API 元素提供文檔注釋,但這并不總是足夠的。對于由多個相互關聯的類組成的復雜 API,通常需要用描述 API 總體架構的外部文檔來補充文檔注釋。如果存在這樣的文檔,相關的類或包文檔注釋應該包含到它的鏈接。
Javadoc automatically checks for adherence to many of the recommendations in this item. In Java 7, the command line switch -Xdoclint was required to get this behavior. In Java 8 and 9, checking is enabled by default. IDE plug-ins such as checkstyle go further in checking for adherence to these recommendations [Burn01]. You can also reduce the likelihood of errors in doc comments by running the HTML files generated by Javadoc through an HTML validity checker. This will detect many incorrect uses of HTML tags. Several such checkers are available for download, and you can validate HTML on the web using the W3C markup validation service [W3C-validator]. When validating generated HTML, keep in mind that as of Java 9, Javadoc is capable of generating HTML5 as well as HTML 4.01, though it still generates HTML 4.01 by default. Use the -html5 command line switch if you want Javadoc to generate HTML5.
Javadoc 會自動檢查文檔是否符合本項目中提及的許多建議。在 Java 7 中,需要命令行開關 `-Xdoclint` 來獲得這種特性。在 Java 8 和 Java 9 中,默認情況下啟用了該機制。諸如 checkstyle 之類的 IDE 插件在檢查是否符合這些建議方面做得更好 [Burn01]。還可以通過 HTML 有效性檢查器運行 Javadoc 生成的 HTML 文件來降低文檔注釋中出現錯誤的可能性。這將檢測 HTML 標記的許多不正確用法。有幾個這樣的檢查器可供下載,你可以使用 W3C 標記驗證服務 [W3C-validator] 在 web 上驗證 HTML。在驗證生成的 HTML 時,請記住,從 Java 9 開始,Javadoc 就能夠生成 HTML 5 和 HTML 4.01,盡管默認情況下它仍然生成 HTML 4.01。如果希望 Javadoc 生成 HTML5,請使用 `-html5` 命令行開關。
The conventions described in this item cover the basics. Though it is fifteen years old at the time of this writing, the definitive guide to writing doc comments is still How to Write Doc Comments [Javadoc-guide]. If you adhere to the guidelines in this item, the generated documentation should provide a clear description of your API. The only way to know for sure, however, is to **read the web pages generated by the Javadoc utility.** It is worth doing this for every API that will be used by others. Just as testing a program almost inevitably results in some changes to the code, reading the documentation generally results in at least a few minor changes to the doc comments.
本條目中描述的約定涵蓋了基本內容。盡管撰寫本文時已經有 15 年的歷史,但編寫文檔注釋的最終指南仍然是《How to Write Doc Comments》[Javadoc-guide]。如果你遵循本條目中的指導原則,生成的文檔應該提供對 API 的清晰描述。然而,唯一確定的方法是 **讀取 Javadoc 實用程序生成的 web 頁面。** 對于其他人將使用的每個 API 都值得這樣做。正如測試程序幾乎不可避免地會導致對代碼的一些更改一樣,閱讀文檔通常也會導致對文檔注釋的一些較小更改。
To summarize, 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 in documentation comments and that HTML metacharacters must be escaped.
總之,文檔注釋是記錄API的最佳、最有效的方法。應該認為,所有公開的 API 元素都必須使用文檔注釋,并采用符合標準約定的統一樣式。請記住,在文檔注釋中允許使用任意 HTML 標簽,并且必須轉義 HTML 元字符。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-8/Chapter-8-Introduction.md)**
- **Previous Item(上一條目):[Item 55: Return optionals judiciously(明智地的返回 Optional)](/Chapter-8/Chapter-8-Item-55-Return-optionals-judiciously.md)**
- **Next Item(下一條目):[Chapter 9 Introduction(章節介紹)](/Chapter-9/Chapter-9-Introduction.md)**
- Chapter 2. Creating and Destroying Objects(創建和銷毀對象)
- Item 1: Consider static factory methods instead of constructors(考慮以靜態工廠方法代替構造函數)
- Item 2: Consider a builder when faced with many constructor parameters(在面對多個構造函數參數時,請考慮構建器)
- Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構造函數或枚舉類型實施單例屬性)
- Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)
- Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源)
- Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)
- Item 7: Eliminate obsolete object references(排除過時的對象引用)
- Item 8: Avoid finalizers and cleaners(避免使用終結器和清除器)
- Item 9: Prefer try with resources to try finally(使用 try-with-resources 優于 try-finally)
- Chapter 3. Methods Common to All Objects(對象的通用方法)
- Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)
- Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法)
- Item 12: Always override toString(始終覆蓋 toString 方法)
- Item 13: Override clone judiciously(明智地覆蓋 clone 方法)
- Item 14: Consider implementing Comparable(考慮實現 Comparable 接口)
- Chapter 4. Classes and Interfaces(類和接口)
- Item 15: Minimize the accessibility of classes and members(盡量減少類和成員的可訪問性)
- Item 16: In public classes use accessor methods not public fields(在公共類中,使用訪問器方法,而不是公共字段)
- Item 17: Minimize mutability(減少可變性)
- Item 18: Favor composition over inheritance(優先選擇復合而不是繼承)
- Item 19: Design and document for inheritance or else prohibit it(繼承要設計良好并且具有文檔,否則禁止使用)
- Item 20: Prefer interfaces to abstract classes(接口優于抽象類)
- Item 21: Design interfaces for posterity(為后代設計接口)
- Item 22: Use interfaces only to define types(接口只用于定義類型)
- Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)
- Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
- Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)
- Chapter 5. Generics(泛型)
- Item 26: Do not use raw types(不要使用原始類型)
- Item 27: Eliminate unchecked warnings(消除 unchecked 警告)
- Item 28: Prefer lists to arrays(list 優于數組)
- Item 29: Favor generic types(優先使用泛型)
- Item 30: Favor generic methods(優先使用泛型方法)
- Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)
- Item 32: Combine generics and varargs judiciously(明智地合用泛型和可變參數)
- Item 33: Consider typesafe heterogeneous containers(考慮類型安全的異構容器)
- Chapter 6. Enums and Annotations(枚舉和注解)
- Item 34: Use enums instead of int constants(用枚舉類型代替 int 常量)
- Item 35: Use instance fields instead of ordinals(使用實例字段替代序數)
- Item 36: Use EnumSet instead of bit fields(用 EnumSet 替代位字段)
- Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)
- Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉)
- Item 39: Prefer annotations to naming patterns(注解優于命名模式)
- Item 40: Consistently use the Override annotation(堅持使用 @Override 注解)
- Item 41: Use marker interfaces to define types(使用標記接口定義類型)
- Chapter 7. Lambdas and Streams(λ 表達式和流)
- Item 42: Prefer lambdas to anonymous classes(λ 表達式優于匿名類)
- Item 43: Prefer method references to lambdas(方法引用優于 λ 表達式)
- Item 44: Favor the use of standard functional interfaces(優先使用標準函數式接口)
- Item 45: Use streams judiciously(明智地使用流)
- Item 46: Prefer side effect free functions in streams(在流中使用無副作用的函數)
- Item 47: Prefer Collection to Stream as a return type(優先選擇 Collection 而不是流作為返回類型)
- Item 48: Use caution when making streams parallel(謹慎使用并行流)
- Chapter 8. Methods(方法)
- Item 49: Check parameters for validity(檢查參數的有效性)
- Item 50: Make defensive copies when needed(在需要時制作防御性副本)
- Item 51: Design method signatures carefully(仔細設計方法簽名)
- Item 52: Use overloading judiciously(明智地使用重載)
- Item 53: Use varargs judiciously(明智地使用可變參數)
- Item 54: Return empty collections or arrays, not nulls(返回空集合或數組,而不是 null)
- Item 55: Return optionals judiciously(明智地的返回 Optional)
- Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
- Chapter 9. General Programming(通用程序設計)
- Item 57: Minimize the scope of local variables(將局部變量的作用域最小化)
- Item 58: Prefer for-each loops to traditional for loops(for-each 循環優于傳統的 for 循環)
- Item 59: Know and use the libraries(了解并使用庫)
- Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)
- Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
- Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)
- Item 63: Beware the performance of string concatenation(當心字符串連接引起的性能問題)
- Item 64: Refer to objects by their interfaces(通過接口引用對象)
- Item 65: Prefer interfaces to reflection(接口優于反射)
- Item 66: Use native methods judiciously(明智地使用本地方法)
- Item 67: Optimize judiciously(明智地進行優化)
- Item 68: Adhere to generally accepted naming conventions(遵守被廣泛認可的命名約定)
- Chapter 10. Exceptions(異常)
- Item 69: Use exceptions only for exceptional conditions(僅在確有異常條件下使用異常)
- Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)
- Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常)
- Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)
- Item 73: Throw exceptions appropriate to the abstraction(拋出能用抽象解釋的異常)
- Item 74: Document all exceptions thrown by each method(為每個方法記錄會拋出的所有異常)
- Item 75: Include failure capture information in detail messages(異常詳細消息中應包含捕獲失敗的信息)
- Item 76: Strive for failure atomicity(盡力保證故障原子性)
- Item 77: Don’t ignore exceptions(不要忽略異常)
- Chapter 11. Concurrency(并發)
- Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
- Item 79: Avoid excessive synchronization(避免過度同步)
- Item 80: Prefer executors, tasks, and streams to threads(Executor、task、流優于直接使用線程)
- Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)
- Item 82: Document thread safety(文檔應包含線程安全屬性)
- Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)
- Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)
- Chapter 12. Serialization(序列化)
- Item 85: Prefer alternatives to Java serialization(優先選擇 Java 序列化的替代方案)
- Item 86: Implement Serializable with great caution(非常謹慎地實現 Serializable)
- Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)
- Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法)
- Item 89: For instance control, prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)
- Item 90: Consider serialization proxies instead of serialized instances(考慮以序列化代理代替序列化實例)