代碼注釋是架起程序設計者與程序閱讀者之間的通信橋梁,最大限度的提高團隊開發合作效率。也是程序代碼可維護性的重要環節之一。所以我們不是為寫注釋而寫注釋。下面說一下我們在訴求網二期開發中使用的代碼注釋規范,供大家參考下。
原則:
1、注釋形式統一
在整個應用程序中,使用具有一致的標點和結構的樣式來構造注釋。如果在其它項目中發現它們的注釋規范與這份文檔不同,按照這份規范寫代碼,不要試圖在既成的規范系統中引入新的規范。
2、注釋內容准確簡潔
內容要簡單、明了、含義准確,防止注釋的多義性,錯誤的注釋不但無益反而有害。
注釋條件:
1、基本注釋(必須加)
(a) 類(接口)的注釋
(b) 構造函數的注釋
(c) 方法的注釋
(d) 全局變量的注釋
(e) 字段/屬性的注釋
備注:簡單的代碼做簡單注釋,注釋內容不大於10個字即可,另外,持久化對象或VO對象的getter、setter方法不需加注釋。具體的注釋格式請參考下面舉例。
2、特殊必加注釋(必須加)
(a) 典型算法必須有注釋。
(b) 在代碼不明晰處必須有注釋。
(c) 在代碼修改處加上修改標識的注釋。
(d) 在循環和邏輯分支組成的代碼中加注釋。
(e) 為他人提供的接口必須加詳細注釋。
備注:此類注釋格式暫無舉例。具體的注釋格式自行定義,要求注釋內容准確簡潔。
注釋格式:
1、單行(single-line)注釋:“//……”
2、塊(block)注釋:“/*……*/”
3、文檔注釋:“/**……*/”
4、javadoc 注釋標簽語法
@author 對類的說明 標明開發該類模塊的作者, 每個作者對應一個標簽。
@version 對類的說明 標明該類模塊的版本
@see 對類、屬性、方法的說明 參考轉向,也就是相關主題 一般ClassName是包括包名的全名
@param 對方法的說明 對方法中某參數的說明
@return 對方法的說明 對方法返回值的說明 一個參數對應一個標簽
@exception 對方法的說明 對方法可能拋出的異常進行說明
或 @throws name description成員方法描述方法拋出的異常,每一個異常對應一個標簽
@data類/接口/方法用於顯示類,方法,接口具體創建時間,或者修改時間
@inheritDoc類/接口/成員方法繼承的文檔
{@link address} 或者
@ linkplain address text}類/接口/方法用於創建一個指向另一份文檔的超鏈接
@Time 2019年6月28日 22:15:22
{@link #hashCode()}
參考舉例
1. 類(接口)注釋
/** * 類的描述 * @author Administrator * @Time 2012-11-2014:49:01 * */ public classTest extends Button { …… }
2. 構造方法注釋
例如: public class Test extends Button { /** * 構造方法 的描述 * @param name * 按鈕的上顯示的文字 */ public Test(String name){ …… } }
3. 方法注釋
例如 public class Test extends Button { /** * 為按鈕添加顏色 *@param color 按鈕的顏色 *@return *@exception (方法有異常的話加) * @author Administrator * @Time2012-11-20 15:02:29 */ public voidaddColor(String color){ …… } }
4. 全局變量注釋
public final class String implements java.io.Serializable, Comparable<String>,CharSequence { /** The value is used for characterstorage. */ private final char value[]; /** The offset is the first index of thestorage that is used. */ private final int offset; /** The count is the number of charactersin the String. */ private final int count; /** Cache the hash code for the string */ private int hash; // Default to 0 …… }
5. 字段/屬性注釋
public class EmailBody implements Serializable{ private String id; private String senderName;//發送人姓名 private String title;//不能超過120個中文字符 private String content;//郵件正文 private String attach;//附件,如果有的話 private String totalCount;//總發送人數 private String successCount;//成功發送的人數 private Integer isDelete;//0不刪除 1刪除 private Date createTime;//目前不支持定時 所以創建后即刻發送 privateSet<EmailList> EmailList; …… }
6.包的注釋
package-info.java -
/** * Provides the classes necessary to create an applet and the classes an applet uses * to communicate with its applet context. * <p> * The applet framework involves two entities: * the applet and the applet context. An applet is an embeddable window (see the * {@link java.awt.Panel} class) with a few extra methods that the applet context * can use to initialize, start, and stop the applet. * * @since 1.0 * @see java.awt */ package java.lang.applet;
其實規范是自己訂的,只要團隊中大家都統一遵守,統一規范,就會取得好的效果,希望對平時不加注釋的朋友有點幫助。
詳見:https://blog.csdn.net/huangsiqian/article/details/82725214