6.3 布局(Placement) 
只在代码块的开始处声明变量。(一个块是指任何被包含在大括号"{"和"}"中间的代码。)不要在首次用到该变量时才声明之。这会把注意力不集中的程序员搞糊涂,同时会妨碍代码在该作用域内的可移植性。 
 

 void myMethod()
void myMethod()  {
{ 
 int int1 = 0; // beginning of method block
int int1 = 0; // beginning of method block 


 if (condition)
if (condition)  {
{ 
 int int2 = 0; // beginning of "if" block
int int2 = 0; // beginning of "if" block 

 
 
 }
} 
 }
} 


该规则的一个例外是for循环的索引变量 
 

 for (int i = 0; i < maxLoops; i++)
for (int i = 0; i < maxLoops; i++)  {
{  }
 } 
避免声明的局部变量覆盖上一级声明的变量。例如,不要在内部代码块中声明相同的变量名: 
 
 int count;
int count; 

 
 

 myMethod()
myMethod()  {
{ 

 if (condition)
if (condition)  {
{ 
 int count = 0; // AVOID!
int count = 0; // AVOID! 

 
 
 }
} 

 
 
 }
} 

6.4 类和接口的声明(Class and Interface Declarations) 
当编写类和接口是,应该遵守以下格式规则: 
- 在方法名与其参数列表之前的左括号"("间不要有空格 
- 左大括号"{"位于声明语句同行的末尾 
- 右大括号"}"另起一行,与相应的声明语句对齐,除非是一个空语句,"}"应紧跟在"{"之后 
 

 class Sample extends Object
class Sample extends Object  {
{ 
 int ivar1;
int ivar1; 
 int ivar2;
int ivar2; 


 Sample(int i, int j)
Sample(int i, int j)  {
{ 
 ivar1 = i;
ivar1 = i; 
 ivar2 = j;
ivar2 = j; 
 }
} 


 int emptyMethod()
int emptyMethod()  {}
{} 


 
 
 }
}

 
- 方法与方法之间以空行分隔 
7 语句(Statements) 
7.1 简单语句(Simple Statements) 
每行至多包含一条语句,例如: 
 
 argv++; // Correct
argv++; // Correct 
 argc--; // Correct
argc--; // Correct 
 argv++; argc--; // AVOID!
argv++; argc--; // AVOID! 

7.2 复合语句(Compound Statements) 
复合语句是包含在大括号中的语句序列,形如"{ 语句 }"。例如下面各段。 
- 被括其中的语句应该较之复合语句缩进一个层次 
- 左大括号"{"应位于复合语句起始行的行尾;右大括号"}"应另起一行并与复合语句首行对齐。 
- 大括号可以被用于所有语句,包括单个语句,只要这些语句是诸如if-else或for控制结构的一部分。这样便于添加语句而无需担心由于忘了加括号而引入bug。 
7.3 返回语句(return Statements) 
一个带返回值的return语句不使用小括号"()",除非它们以某种方式使返回值更为显见。例如: 
 
 return;
return; 

 return myDisk.size();
return myDisk.size(); 

 return (size ? size : defaultSize);
return (size ? size : defaultSize); 

 
7.4 if,if-else,if else-if else语句(if, if-else, if else-if else Statements) 
if-else语句应该具有如下格式: 
 

 if (condition)
if (condition)  {
{ 
 statements;
statements; 
 }
} 


 if (condition)
if (condition)  {
{ 
 statements;
statements; 

 } else
} else  {
{ 
 statements;
statements; 
 }
} 


 if (condition)
if (condition)  {
{ 
 statements;
statements; 

 } else if (condition)
} else if (condition)  {
{ 
 statements;
statements; 

 } else
} else {
{ 
 statements;
statements; 
 }
} 


注意:if语句总是用"{"和"}"括起来,避免使用如下容易引起错误的格式: 
 
 if (condition) //AVOID! THIS OMITS THE BRACES {}!
if (condition) //AVOID! THIS OMITS THE BRACES {}! 
 statement;
statement;  
7.5 for语句(for Statements) 
一个for语句应该具有如下格式: 
 

 for (initialization; condition; update)
for (initialization; condition; update)  {
{ 
 statements;
statements; 
 }
} 

一个空的for语句(所有工作都在初始化,条件判断,更新子句中完成)应该具有如下格式: 
 
 for (initialization; condition; update);
for (initialization; condition; update); 
当在for语句的初始化或更新子句中使用逗号时,避免因使用三个以上变量,而导致复杂度提高。若需要,可以在for循环之前(为初始化子句)或for循环末尾(为更新子句)使用单独的语句。 
7.6 while语句(while Statements) 
一个while语句应该具有如下格式 
 

 while (condition)
while (condition)  {
{ 
 statements;
statements; 
 }
} 

一个空的while语句应该具有如下格式: 
 
 while (condition);
while (condition);  
7.7 do-while语句(do-while Statements) 
一个do-while语句应该具有如下格式: 
 

 do
do  {
{ 
 statements;
statements; 
 } while (condition);
} while (condition); 

7.8 switch语句(switch Statements) 
一个switch语句应该具有如下格式: 
 

 switch (condition)
switch (condition)  {
{ 
 case ABC:
case ABC: 
 statements;
statements; 

 /**//* falls through */
/**//* falls through */ 
 case DEF:
case DEF: 
 statements;
statements; 
 break;
break; 

 case XYZ:
case XYZ: 
 statements;
statements; 
 break;
break; 

 default:
default: 
 statements;
statements; 
 break;
break; 
 }
} 


每当一个case顺着往下执行时(因为没有break语句),通常应在break语句的位置添加注释。上面的示例代码中就包含注释/* falls through */。 
7.9 try-catch语句(try-catch Statements) 
一个try-catch语句应该具有如下格式: 
 

 try
try  {
{ 
 statements;
statements; 

 } catch (ExceptionClass e)
} catch (ExceptionClass e)  {
{ 
 statements;
statements; 
 }
}  
一个try-catch语句后面也可能跟着一个finally语句,不论try代码块是否顺利执行完,它都会被执行。 
 

 try
try  {
{ 
 statements;
statements; 

 } catch (ExceptionClass e)
} catch (ExceptionClass e)  {
{ 
 statements;
statements; 

 } finally
} finally  {
{ 
 statements;
statements; 
 }
} 

8 空白(White Space) 
8.1 空行(Blank Lines) 
空行将逻辑相关的代码段分隔开,以提高可读性。 
下列情况应该总是使用两个空行: 
- 一个源文件的两个片段(section)之间 
- 类声明和接口声明之间 
下列情况应该总是使用一个空行: 
- 两个方法之间 
- 方法内的局部变量和方法的第一条语句之间 
- 块注释(参见"5.1.1")或单行注释(参见"5.1.2")之前 
- 一个方法内的两个逻辑段之间,用以提高可读性 
8.2 空格(Blank Spaces) 
下列情况应该使用空格: 
- 一个紧跟着括号的关键字应该被空格分开,例如: 
注意:空格不应该置于方法名与其左括号之间。这将有助于区分关键字和方法调用。 
- 空白应该位于参数列表中逗号的后面 
- 所有的二元运算符,除了".",应该使用空格将之与操作数分开。一元操作符和操作数之间不因该加空格,比如:负号("-")、自增("++")和自减("--")。例如: 
 a += c + d;
a += c + d; 
 a = (a + b) / (c * d);
a = (a + b) / (c * d); 


 while (d++ = s++)
while (d++ = s++)  {
{ 
 n++;
n++; 
 }
} 
 printSize("size is " + foo + "\n");
printSize("size is " + foo + "\n"); 

 
- for语句中的表达式应该被空格分开,例如: 
 for (expr1; expr2; expr3)
for (expr1; expr2; expr3)  
- 强制转型后应该跟一个空格,例如: 
 myMethod((byte) aNum, (Object) x);
myMethod((byte) aNum, (Object) x); 
 myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
myMethod((int) (cp + 5), ((int) (i + 3)) + 1); 
9 命名规范(Naming Conventions) 
命名规范使程序更易读,从而更易于理解。它们也可以提供一些有关标识符功能的信息,以助于理解代码,例如,不论它是一个常量,包,还是类。 
 
包(Packages) 一个唯一包名的前缀总是全部小写的ASCII字母并且是一个顶级域名,通常是com,edu,gov,mil,net,org,或1981年ISO 3166标准所指定的标识国家的英文双字符代码。包名的后续部分根据不同机构各自内部的命名规范而不尽相同。这类命名规范可能以特定目录名的组成来区分部门(department),项目(project),机器(machine),或注册名(login names)。 
 com.sun.engcom.apple.quicktime.v2edu.cmu.cs.bovik.cheese
com.sun.engcom.apple.quicktime.v2edu.cmu.cs.bovik.cheese 
类(Classes) 命名规则:类名是个一名词,采用大小写混合的方式,每个单词的首字母大写。尽量使你的类名简洁而富于描述。使用完整单词,避免缩写词(除非该缩写词被更广泛使用,像URL,HTML) class Raster;class ImageSprite; 
接口(Interfaces) 命名规则:大小写规则与类名相似 interface RasterDelegate;interface Storing; 
方法(Methods) 方法名是一个动词,采用大小写混合的方式,第一个单词的首字母小写,其后单词的首字母大写。 run();runFast();getBackground(); 
变量(Variables) 除了变量名外,所有实例,包括类,类常量,均采用大小写混合的方式,第一个单词的首字母小写,其后单词的首字母大写。变量名不应以下划线或美元符号开头,尽管这在语法上是允许的。变量名应简短且富于描述。变量名的选用应该易于记忆,即,能够指出其用途。尽量避免单个字符的变量名,除非是一次性的临时变量。临时变量通常被取名为i,j,k,m和n,它们一般用于整型;c,d,e,它们一般用于字符型。 char c;int i;float myWidth; 
实例变量(Instance Variables) 大小写规则和变量名相似,除了前面需要一个下划线 int _employeeId;String _name;Customer _customer; 
常量(Constants) 类常量和ANSI常量的声明,应该全部大写,单词间用下划线隔开。(尽量避免ANSI常量,容易引起错误) static final int MIN_WIDTH = 4;static final int MAX_WIDTH = 999;static final int GET_THE_CPU = 1; 
10 编程惯例(Programming Practices)
10.1 提供对实例以及类变量的访问控制(Providing Access to Instance and Class Variables) 
若没有足够理由,不要把实例或类变量声明为公有。通常,实例变量无需显式的设置(set)和获取(gotten),通常这作为方法调用的边缘效应 (side effect)而产生。 
一个具有公有实例变量的恰当例子,是类仅作为数据结构,没有行为。亦即,若你要使用一个结构(struct)而非一个类(如果java支持结构的话),那么把类的实例变量声明为公有是合适的。
 
10.2 引用类变量和类方法(Referring to Class Variables and Methods) 
避免用一个对象访问一个类的静态变量和方法。应该用类名替代。例如: 
 classMethod(); //OK
classMethod(); //OK 
 AClass.classMethod(); //OK
AClass.classMethod(); //OK 
 anObject.classMethod(); //AVOID!
anObject.classMethod(); //AVOID!  
10.3 常量(Constants) 
位于for循环中作为计数器值的数字常量,除了-1,0和1之外,不应被直接写入代码。
 
10.4 变量赋值(Variable Assignments) 
避免在一个语句中给多个变量赋相同的值。它很难读懂。例如: 
 fooBar.fChar = barFoo.lchar = ´c´; // AVOID!
fooBar.fChar = barFoo.lchar = ´c´; // AVOID! 
不要将赋值运算符用在容易与相等关系运算符混淆的地方。例如: 

 if (c++ = d++)
if (c++ = d++)  { // AVOID! (Java disallows)
{ // AVOID! (Java disallows) 

 
 
 }
}  
应该写成 

 if ((c++ = d++) != 0)
if ((c++ = d++) != 0)  {
{ 

 
 
 }
} 
不要使用内嵌(embedded)赋值运算符试图提高运行时的效率,这是编译器的工作。例如: 
 d = (a = b + c) + r; // AVOID!
d = (a = b + c) + r; // AVOID! 

 应该写成
应该写成 
 a = b + c;
a = b + c; 
 d = a + r;
d = a + r; 

 
10.5 其它惯例(Miscellaneous Practices) 
10.5.1 圆括号(Parentheses) 
一般而言,在含有多种运算符的表达式中使用圆括号来避免运算符优先级问题,是个好方法。即使运算符的优先级对你而言可能很清楚,但对其他人未必如此。你不能假设别的程序员和你一样清楚运算符的优先级。 
 if (a == b && c == d) // AVOID!
if (a == b && c == d) // AVOID! 
 if ((a == b) && (c == d)) // RIGHT
if ((a == b) && (c == d)) // RIGHT 
10.5.2 返回值(Returning Values) 
设法让你的程序结构符合目的。例如: 

 if (booleanExpression)
if (booleanExpression)  {
{ 
 return true;
return true; 

 } else
} else  {
{ 
 return false;
return false; 
 }
} 

 应该代之以如下方法:
应该代之以如下方法: 
 return booleanExpression;
return booleanExpression; 

 类似地:
类似地: 

 if (condition)
if (condition)  {
{ 
 return x;
return x; 
 }
} 
 return y;
return y; 

 应该写做:
应该写做: 
 return (condition ? x : y);
return (condition ? x : y); 


10.5.3 条件运算符"?"前的表达式(Expressions before ´?´ in the Conditional Operator) 
如果一个包含二元运算符的表达式出现在三元运算符" ? : "的"?"之前,那么应该给表达式添上一对圆括号。例如: 
 (x >= 0) ? x : -x;
(x >= 0) ? x : -x; 
10.5.4 特殊注释(Special Comments) 
在注释中使用XXX来标识某些未实现(bogus)的但可以工作(works)的内容。用FIXME来标识某些假的和错误的内容。 
11 代码范例(Code Examples)
11.1 Java源文件范例(Java Source File Example) 
下面的例子,展示了如何合理布局一个包含单一公共类的Java源程序。接口的布局与其相似。更多信息参见"类和接口声明"以及"文挡注释"。 

 /**//*
/**//* 
 * @(#)Blah.java 1.82 99/03/18
* @(#)Blah.java 1.82 99/03/18 
 *
* 
 * Copyright (c) 1994-1999 Sun Microsystems, Inc.
* Copyright (c) 1994-1999 Sun Microsystems, Inc. 
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
* 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. 
 * All rights reserved.
* All rights reserved. 
 *
* 
 * This software is the confidential and proprietary information of Sun
* This software is the confidential and proprietary information of Sun 
 * Microsystems, Inc. ("Confidential Information"). You shall not
* Microsystems, Inc. ("Confidential Information"). You shall not 
 * disclose such Confidential Information and shall use it only in
* disclose such Confidential Information and shall use it only in 
 * accordance with the terms of the license agreement you entered into
* accordance with the terms of the license agreement you entered into 
 * with Sun.
* with Sun. 
 */
*/ 


 package java.blah;
package java.blah; 

 import java.blah.blahdy.BlahBlah;
import java.blah.blahdy.BlahBlah; 


 /** *//**
/** *//** 
 * Class description goes here.
* Class description goes here. 
 *
* 
 * @version 1.82 18 Mar 1999
* @version 1.82 18 Mar 1999 
 * @author Firstname Lastname
* @author Firstname Lastname 
 */
*/ 

 public class Blah extends SomeClass
public class Blah extends SomeClass  {
{ 

 /**//* A class implementation comment can go here. */
/**//* A class implementation comment can go here. */ 


 /** *//** classVar1 documentation comment */
/** *//** classVar1 documentation comment */ 
 public static int classVar1;
public static int classVar1; 


 /** *//**
/** *//** 
 * classVar2 documentation comment that happens to be
* classVar2 documentation comment that happens to be 
 * more than one line long
* more than one line long 
 */
*/ 
 private static Object classVar2;
private static Object classVar2; 


 /** *//** instanceVar1 documentation comment */
/** *//** instanceVar1 documentation comment */ 
 public Object instanceVar1;
public Object instanceVar1; 


 /** *//** instanceVar2 documentation comment */
/** *//** instanceVar2 documentation comment */ 
 protected int instanceVar2;
protected int instanceVar2; 


 /** *//** instanceVar3 documentation comment */
/** *//** instanceVar3 documentation comment */ 
 private Object[] instanceVar3;
private Object[] instanceVar3; 


 /** *//**
/** *//** 
 *
*  constructor Blah documentation comment
constructor Blah documentation comment 
 
 */
*/ 

 public Blah()
public Blah()  {
{ 
 //
//  implementation goes here
implementation goes here 
 
 }
} 


 /** *//**
/** *//** 
 *
*  method doSomething documentation comment
method doSomething documentation comment 
 
 */
*/ 

 public void doSomething()
public void doSomething()  {
{ 
 //
//  implementation goes here
implementation goes here 
 
 }
} 


 /** *//**
/** *//** 
 *
*  method doSomethingElse documentation comment
method doSomethingElse documentation comment 
 
 * @param someParam description
* @param someParam description 
 */
*/ 

 public void doSomethingElse(Object someParam)
public void doSomethingElse(Object someParam)  {
{ 
 //
//  implementation goes here
implementation goes here 
 
 }
} 
 }
} 
