java编码代码规范 java编码规范和格式的要求(11)


statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else{
statements;
}
注意:if语句总是用"{"和"}"括起来,避免使用如下容易引起错误的格式:
if (condition) //AVOID! THIS OMITS THE BRACES {}!
statement;
7.5 for语句(for Statements)
一个for语句应该具有如下格式:
for (initialization; condition; update) {
statements;
}
一个空的for语句(所有工作都在初始化,条件判断,更新子句中完成)应该具有如下格式:
for (initialization; condition; update);
当在for语句的初始化或更新子句中使用逗号时,避免因使用三个以上变量,而导致复杂度提高 。若需要,可以在for循环之前(为初始化子句)或for循环末尾(为更新子句)使用单独的语句 。
7.6 while语句(while Statements)
一个while语句应该具有如下格式
while (condition) {
statements;
}
一个空的while语句应该具有如下格式:
while (condition);
7.7 do-while语句(do-while Statements)
一个do-while语句应该具有如下格式:
do {
statements;
} while (condition);
7.8 switch语句(switch Statements)
一个switch语句应该具有如下格式:
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
每当一个case顺着往下执行时(因为没有break语句),通常应在break语句的位置添加注释 。上面的示例代码中就包含注释/* falls through */ 。
7.9 try-catch语句(try-catch Statements)
一个try-catch语句应该具有如下格式:
try {
statements;
} catch (ExceptionClass e) {
statements;
}
一个try-catch语句后面也可能跟着一个finally语句,不论try代码块是否顺利执行完,它都会被执行 。
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
8 空白(White Space)
8.1 空行(Blank Lines)
空行将逻辑相关的代码段分隔开 , 以提高可读性 。
下列情况应该总是使用两个空行:
- 一个源文件的两个片段(section)之间
- 类声明和接口声明之间
下列情况应该总是使用一个空行:
- 两个方法之间
- 方法内的局部变量和方法的第一条语句之间
- 块注释(参见"5.1.1")或单行注释(参见"5.1.2")之前
- 一个方法内的两个逻辑段之间,用以提高可读性
8.2 空格(Blank Spaces)
下列情况应该使用空格:
- 一个紧跟着括号的关键字应该被空格分开 , 例如:
while (true) {
...
}
注意:空格不应该置于方法名与其左括号之间 。这将有助于区分关键字和方法调用 。
- 空白应该位于参数列表中逗号的后面
- 所有的二元运算符,除了".",应该使用空格将之与操作数分开 。一元操作符和操作数之间不因该加空格,比如:负号("-")、自增("++")和自减("--") 。例如:
a += c + d;
a = (a + b) / (c * d);
while (d++ = s++) {
n++;
}
printSize("size is " + foo + "\n");
- for语句中的表达式应该被空格分开,例如:
for (expr1; expr2; expr3)
- 强制转型后应该跟一个空格,例如:
myMethod((byte) aNum, (Object) x);
myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
9 命名规范(Naming Conventions)
命名规范使程序更易读,从而更易于理解 。它们也可以提供一些有关标识符功能的信息,以助于理解代码,例如 , 不论它是一个常量 , 包,还是类 。

推荐阅读