Java代码书写规范
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
◆符号命名规则
符号名包括:模块名,变量名,常量名,方法(函数/子程序)名,数据区名,缓冲区名等。
符号命名通常应遵循以下规则:
通用规则:
1、在所有命名中,都应使用标准的英文单词或缩写。
不得使用拼音或拼音缩写,除非该名字描述的是中文特有的内容,如半角、全角, 声母、韵母等。
2、所有命名都应遵循达意原则,即名称应含义清晰、明确。
3、所有命名都不易过长,应控制在规定的最大长度以内。
4、所有命名都应尽量使用全称。
5、如果命名使用缩写,则必须对其进行注释和说明。
具体规范:
1、工程名统一制订。
2、文件名
文件名应与类名相同,这是java的规范
3、方法名/函数名
✧·方法名第一个单词小写。
✧·推荐使用动宾结构。
方法名应清晰反映该方法的功能、用途。
✧·方法名最长不得超过30个字符。
例:
getCollection();
setCollection();
insertObject();
deleteObject();
3、变量名
必须使用有意义的变量名。
推荐的类型缩写(type)——
·char:ch
·boolean:b
·int:i
·long:l
·double:d
·float:f
变量名最长不得超过20个字符。
4、类名
✧·必须以大写字母开头,类名反映具体含义,以清晰表达类的用途和功能为
原则
✧·当名称由多个单词构成时,每一个单词的第一个字母必须大写
◆代码书写规范
书写规范即在编写代码过程中所使用的标准格式,主要包括空格的使用、括号的使用、缩近格式和其他一些内容。
源代码书写规范
1.在.java/.jsp的开头应有一段格式统一的说明,内容包括:
a. 文件名(Title/FileName);
b. 创建人(Author);
c. 文件创建时间(Date);
d. 简短说明文件功能、用途(Description /Function)。
样例:
/**
* 标题: Schedule.java
* 描述: 用来实现计划项目审批
* 创建: 2001-06-30
* 作者: 赵文正
* 详细:详细描述计划项目审批的细节,如何根据细节功能确定方法
*/
2. 除非极其简单,否则对函数应有注释说明。
内容包括:功能、入口/出口参数,必要时还可有备注或补充说明。
3. 每行代码的长度推荐为80列,最长不得超过120列;折行以对齐为准。
4. 在类的成员函数内调用其他类的成员函数时,其他类的成员函数可做简短说明。
6. 函数入口参数有缺省值时,应注释说明。
例:
float getValue(int ID, boolean flag) {
/* parameter description
ID: Identify No
flag : default = TRUE
*/
…
}
7. else if 必须写在一行。
8. 与‘{’、‘}’有关的各项规定:
①‘{’、‘}’应独占一行。
在该行内可有注释。
例:正确:
for (i = 0; i <Line; i++)
{ // .....
System.out.println("Line="+ i+”value = ”+Lines[i]);
}
不得写做:
for (i = 0; i < cb; i++)
{ System.out.println("Line="+ i+”value = ”+Lines[i]);
}
②‘{’必须另起一行,‘{’之后的代码必须缩进一个Tab。
‘{’与‘}’
必须在同一列上。
例:正确:
if (i > 0)
{
m = 1;
n++;
}
不得写做:
if (i > 0) {
m = 1;
n++;
}
③在循环、分支之后若只有一行代码,虽然可省略‘{’、‘}’,但不
推荐这么做。
若省略后可能引起歧义,则必须加上‘{’、‘}’。
例:正确:
if (n == -2)
{ n = 1; }
else if (n != nTemp)
{ n = 2; }
else
{ n = 3; }
不得写做:
if (n == -2)
n = 1;
else if (n != nTemp)
n = 2;
else
n = 3;
9. 与空格有关的各项规定。
①所有两目、三目运算符的两边都必须有空格。
在单目运算符两端不
必空格。
但在‘.’、‘[’、‘]’等运算符前后,及‘&’(取地址)等运算
符之后不得有空格。
例:正确:
int n = 0, nTemp;
for (int i = nMinLine; i <= nMaxLine; i++)
不得写做:
int n=0, nTemp;
for ( int i=nMinLine; i<=nMaxLine; i++ )
②or、while、if 等关键词之后应有1个空格,再接‘(’,之后无空格;
在结尾的‘)’前不得有空格。
例:正确:
if (-2 == n)
不得写做:
if(-2 == n)
或
if ( -2 == n )
等等。
③调用函数时,‘(’、‘)’前后不得有空格。
④类型强制转换时,‘(’‘)’前后不得有空格
10. 与缩进有关的各项规定
①缩进以Tab 为单位。
1 个Tab 为 4 个空格
②下列情况,代码缩进一个Tab:
函数体相对函数名及‘{’、‘}’。
if、else、for、while、do 等之后的代码。
一行之内写不下,折行之后的代码,应在合理的位置进行折行。
若有+ - * / 等运算符,则运算符应在上一行末尾,而不应在下一行的行首。
③下列情况,不必缩进:switch 之后的case、default。
在switch-case结构中,case语句距离switch 语句的开始应缩进一个TAB,每个case的程序体距离case的开始缩进一个TAB;
举例:
switch (value)
{
case 1:
/* Body for case 1. */
break;
case 2:
/* Body for case 2. */
break;
default:
/* Body for default. */
break;
}
④所有的函数定义和函数定义的花括号都应位于第一列;
⑤所有成对的花括号都应出现在同一列,并与相应的控制语
句同列,在对数组、类、和枚举类型的成员初始化时,同样遵循此规
则;
⑥对于java/jsp程序,强烈建议使用如下结构:
try{
……
}
catch(Exception ex){
……
}
finally {
try {
……
}
catch (Exception e) {
……
}
}
⑦其他
对复杂的条件语句(分支中的语句较多),应在每个结束的花括号后加一条注释说明是哪一个分支的结束,并在分支的开始加注释说明进入分支的条件;复杂的循环程序段遵循此规则;
每个语句占一行;
函数定义时,函数的返值和函数名应在同一行。
程序的注释规范
在项目开发过程中,对代码的注释十分重要,与代码规范一样提供良好的可读性和易维护性,对程序中的每一个文件、类、函数以及重要的变量,都应用相关的注释说明他们的作者、用途和使用方法,对程序中较复杂或重要的部分应说明它们的含义和目的,对后续添加和修改的部分应注明修改者姓名和修改时间。
SUN提供了JavaDoc工具抽取程序中的相关注释:以下都以SUN 的标准(即:JA V A API 规定式样的注释)来说明程序的注释规范,以利于根据程序的注释用Javadoc生成API格式的java 文档。
原则:
✧注释是程序调用者和执行者之间唯一的协议
✧程序异常的注释必须显著的标明注释
✧程序的注释应该能提供足够的信息,根据注释,质量保证人员应该能
够写出测试用例
Javadoc 能够根据以下几类文件中的注释抽取出来生成JA V A API格式的注释:
✧Java源程序,包括源程序,接口,结构的注释
✧包的注释文件
✧一般的注释文件
✧其它文件:包括类文件,applet, HTML等
文档注释的一般格式
文档的注释通常包括两部分。
描述部分和0 到多个标记。
其格式如下例:/**
* This is the description part of a doc comment
*
* @tag Comment for the tag
*/
注:行的长度不超过80个字符
如果有一段以上的注释,要使用<p>进行分段。
注释的检查工具
SUN提供DocCheck工具,用来检查注释风格和标记的错误,并能提供修改建议。
描述部分
描述部分第一句应该是关于该类,接口,包,成员的概括,Javadoc 工具将会copy这一句作为该部分的概括。
例:
/**
* This is a simulation of Prof. Knuth's MIX computer.
*/
Javadoc 会抽取到Prof 为止,作为概述。
不过可以通过 HTML 标记 "&" or "<" 来连接连个句子。
例如 /**
* This is a simulation of Prof. Knuth's MIX computer. */
或者
/**
* This is a simulation of Prof.<!-- --> Knuth's MIX computer. */
以下情况可以不用写注释,Javadoc 会自动生成相应的注释
当一个类的方法重载超类的方法时;
当一个接口中的方法继承父接口中的方法时;
当在类中实现该类继承的接口的方法的时候;
推荐的风格
使用<code>...</code>来标记关键字或重要的名称,如:java 关键字,包名称,类名称,方法名称,接口名称,代码样例等。
使用内嵌的链接{@link}来引起超连结
建议使用短语代替句子,特别是在@param 标记描述的时候
在描述部分中尽量是用第三人称而不是第二人称进行描述,例如:
在描述是尽量是
用动宾结构
Gets the label of this button.
(首选格式) This method gets the label of this (避
Gets the
label.
(首选格式) Get the
label. (避免格式)
button. 免格式)
避免使用拉丁语,例如:应该用"for example"取代"e.g.", 用"that is" 或者"to be specific" 代替"i.e."等等。
标记惯例
java规定1.0版规定了一下描述标记
* @author (类和接口中必须使用此标记)
* @version (类和接口中必须使用此标记)
* @param (只在方法和结构中使用)
* @return (只在方法中使用)
* @exception (如@throws一样,用来表示抛出异常),例如:
/**
* @throws IOException If an input or output exception occurred
*/
public void f() throws IOException {
// body
}
* @see (用来指出参考的部分)
* @since (开始版本)例:
/**
* @since 1.2
*/
* @serial (等同于@serialField 或@serialData表示持续时间)
* @deprecated (不赞成使用),例:
/**
* @deprecated As of JDK 1.1, replaced by setBounds
* @see #setBounds(int,int,int,int)
*/
以上标记如果有多个的话,通常按照字母顺序列出,例如:
@see #field
@see #Constructor(Type, Type...)
@see #Constructor(Type id, Type id...)
@see #method(Type, Type,...)
@see #method(Type id, Type, id...)
@see Class
@see Class#field
@see Class#Constructor(Type, Type...)
@see Class#Constructor(Type id, Type id)
@see Class#method(Type, Type,...)
@see Class#method(Type id, Type id,...)
@see package.Class
@see package.Class#field
@see package.Class#Constructor(Type, Type...)
@see package.Class#Constructor(Type id, Type id)
@see package.Class#method(Type, Type,...)
@see package.Class#method(Type id, Type, id)
@see package
关于java标记基本原则更为详细的说明可见: Javadoc Reference page
程序异常的注释
所有检查过(catch)异常必须注释
未检查的(RuntimeException)但调用的时候可能出现的异常,可适当的进行注释。
包级的注释
javadoc能够根据包的注释文件生成包的概述文件.其过程如下
package.html --------------> package-summary.html
(source file) javadoc (destination file)
Copy 注释文件中<body>和</body>之间的内容作为最为包的概述放入package-summary.html 文件.
处理注释文件中出现的@see, @since or {@link}等Javadoc 标记
Copy 第一句作为总体概述(Overview Summary)
关于package.html的写法,通常有以下2种:
空的包级注释模板,参考:Empty Template for Package-Level Doc Comment File
常用的模板格式如下:
内部类的注释
关于内部类的注释通常如下例:
/**
* The method used for creating the tree. Any structural modifications
* to the display of the Jtree should be done by overriding this method.
* This method adds an anonymous TreeSelectionListener to the returned JTree.
* Upon receiving TreeSelectionEvents, this listener calls refresh with
* the selected node as a parameter.
*/
public JTree makeTree(AreaInfo ai){
}
注释样例
以下是SUN提供的注释样例,以供参考
/**
* Graphics is the abstract base class for all graphics contexts
* which allow an application to draw onto components realized on
* various devices or onto off-screen images.
* A Graphics object encapsulates the state information needed
* for the various rendering operations that Java supports. This
* state information includes:
* <ul>
* <li>The Component to draw on
* <li>A translation origin for rendering and clipping coordinates
* <li>The current clip
* <li>The current color
* <li>The current font
* <li>The current logical pixel operation function (XOR or Paint)
* <li>The current XOR alternation color
* (see <a href="#setXORMode">setXORMode</a>)
* </ul>
* <p>
* Coordinates are infinitely thin and lie between the pixels of the
* output device.
* Operations which draw the outline of a figure operate by traversing * along the infinitely thin path with a pixel-sized pen that hangs
* down and to the right of the anchor point on the path.
* Operations which fill a figure operate by filling the interior
* of the infinitely thin path.
* Operations which render horizontal text render the ascending
* portion of the characters entirely above the baseline coordinate.
* <p>
* Some important points to consider are that drawing a figure that
* covers a given rectangle will occupy one extra row of pixels on
* the right and bottom edges compared to filling a figure that is
* bounded by that same rectangle.
* Also, drawing a horizontal line along the same y coordinate as
* the baseline of a line of text will draw the line entirely below
* the text except for any descenders.
* Both of these properties are due to the pen hanging down and to
* the right from the path that it traverses.
* <p>
* All coordinates which appear as arguments to the methods of this
* Graphics object are considered relative to the translation origin
* of this Graphics object prior to the invocation of the method.
* All rendering operations modify only pixels which lie within the
* area bounded by both the current clip of the graphics context
* and the extents of the Component used to create the Graphics object. *
* @author Sami Shaio
* @author Arthur van Hoff
* @version %I%, %G%
* @since JDK1.0
*/
public abstract class Graphics {
/**
* Draws as much of the specified image as is currently available
* with its northwest corner at the specified coordinate (x, y).
* This method will return immediately in all cases, even if the
* entire image has not yet been scaled, dithered and converted
* for the current output device.
* <p>
* If the current output representation is not yet complete then
* the method will return false and the indicated {@link ImageObserver}
* object will be notified as the conversion process progresses.
*
* @param img the image to be drawn
* @param x the x-coordinate of the northwest corner of the
* destination rectangle in pixels
* @param y the y-coordinate of the northwest corner of the
* destination rectangle in pixels
* @param observer the image observer to be notified as more of the
* image is converted. May be <code>null</code>
* @return <code>true</code> if the image is completely
* loaded and was painted successfully;
* <code>false</code> otherwise.
* @see Image
* @see ImageObserver
* @since JDK1.0
*/
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer);
/**
* Dispose of the system resources used by this graphics context.
* The Graphics context cannot be used after being disposed of.
* While the finalization process of the garbage collector will
* also dispose of the same system resources, due to the number
* of Graphics objects that can be created in short time frames
* it is preferable to manually free the associated resources
* using this method rather than to rely on a finalization
* process which may not happen for a long period of time.
* <p>
* Graphics objects which are provided as arguments to the paint
* and update methods of Components are automatically disposed * by the system when those methods return. Programmers should, * for efficiency, call the dispose method when finished using
* a Graphics object only if it was created directly from a
* Component or another Graphics object.
*
* @see #create
* @see #finalize
* @see Component#getGraphics
* @see Component#paint
* @see Component#update
* @since JDK1.0
*/
public abstract void dispose();
/**
* Disposes of this graphics context once it is no longer referenced.
* @see #dispose
* @since JDK1.0
*/
public void finalize() {
dispose();
}
}。