2021/03/25

[筆記] Effective Java #56 為所有導出的 API 編寫文件注釋

Effective Java 3rd 簡體中文版筆記 #56 為所有導出的 API 編寫文件注釋
如果要讓 API 好用,就應該替它撰寫文件。在每個被導出的 class、介面、constructor、method 及 field 前,增加一個文件注釋。Method 的文件注釋,應描述它與客戶端的約定,列出前置條件 (precondition)後置條件 (postcondition),可以使用 @throws 來針對例外作說明,@param 標記參數的前提條件,@return 說明回傳的意義,更應該要說明方法的副作用 (side effect)
文件注釋中使用 HTML 標籤來編寫,Javadoc 工具可以將它轉成正確的顯示方式。當為泛型或者方法撰寫文件時,確定要將每一個類型參數作說明。
/**
 * 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> { }
當為枚舉 (enum) 撰寫時,要在文件中說明常量的意義。
/**
 * 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;
}
在為註解 (annotation) 撰寫文件時,要在文件中說明所有成員。
/**
 * 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 Throwable> value();
}
轉載請註明原文網址 https://cookieandcoketw.blogspot.com/2021/03/effective-java-56-api.html

沒有留言:

張貼留言