代码注释是架起程序设计者与程序阅读者之间的通信桥梁,最大限度的提高团队开发合作效率。也是程序代码可维护性的重要环节之一。
原则:
1. 注释形式统一
在整个应用程序中,使用具有一致的标点和结构的样式来构造注释。如果在其它项目中发现它们的注释规范与这份文档不同,按照这份规范写代码,不要试图在既成的规范系统中引入新的规范。
1. 注释内容准确简洁
内容要简单、明了、含义准确,防止注释的多义性,错误的注释不但无益反而有害。
注释条件
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 对类、属性、方法的说明参考转向,也就是相关主题
@param 对方法的说明 对方法中某参数的说明
@return 对方法的说明 对方法返回值的说明
@exception 对方法的说明 对方法可能抛出的异常进行说明
注释范例
1. 类(接口)注释
例如:
/**
* Class description goes here.
* @ClassName:Test
* @author Administrator
* @date 2019/6/20
*
*/
public class Test extends Button {
……
}
2. 构造方法注释
例如:
public class Test extends Button {
/**
* Constructor description goes here.
* @param name
* The more description.
*
*/
public Test(String name){
……
}
}
3. 方法注释
例如
public class Test extends Button {
/**
* Fuction description goes here.
* @param color
* @return void
* @exception (If needed)
* @author Administrator
* @date 2019/6/20
*
*/
public voidaddColor(String color){
……
}
}
4. 全局变量注释
例如:
public final class String
implements Java.io.Serializable, Comparable,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. 字段/属性注释
/* classVar1 documentation comment /
public static int classVar1;
/** classVar2 documentation comment that happens to be
* more than one line long
*/
private static Object classVar2;
/* instanceVar1 documentation comment /
public Object instanceVar1;
/* instanceVar2 documentation comment /
protected int instanceVar2;
/* instanceVar3 documentation comment /
private Object[] instanceVar3;
6. 文件注释
/*
* @(#)Blah.java 1.82 99/03/18
*
* Copyright (c) 1994-1999 Sun Microsystems, Inc.
901 San Antonio * Road, Palo Alto, California, 94303, U.S.A.All rights reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. (“Confidential Information”). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Sun.
*/
package java.blah;
import java.blah.blahdy.BlahBlah;
/**
* Class description goes here.
* @version 1.82 18 Mar 1999
* @author Firstname Lastname
*
*/
public class Blah extends SomeClass {
…
}