//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... }
if語句的換行通常使用8個空格的規則,因為常規縮進(4個空格)會使語句體看起來比較費勁。比如: //DON’T USE THIS INDENTATION if ((condition1 && condition2) (condition3 && condition4) !(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS }
//USE THIS INDENTATION INSTEAD if ((condition1 && condition2) (condition3 && condition4) !(condition5 && condition6)) { doSomethingAboutIt(); }
//OR USE THIS if ((condition1 && condition2) (condition3 && condition4) !(condition5 && condition6)) { doSomethingAboutIt(); }
注重:空格不應該置于方法名與其左括號之間。這將有助于區分要害字和方法調用。 - 空白應該位于參數列表中逗號的后面 - 所有的二元運算符,除了".",應該使用空格將之與操作數分開。一元操作符和操作數之間不因該加空格,比如:負號("-")、自增("++")和自減("--")。例如: a += c + d; a = (a + b) / (c * d);
while (d++ = s++) { n++; } printSize("size is " + foo + "");
不要使用內嵌(embedded)賦值運算符試圖提高運行時的效率,這是編譯器的工作。例如: d = (a = b + c) + r; // AVOID!
應該寫成 a = b + c; d = a + r;
10.5 其它慣例(Miscellaneous Practices) 10.5.1 圓括號(Parentheses) 一般而言,在含有多種運算符的表達式中使用圓括號來避免運算符優先級問題,是個好方法。即使運算符的優先級對你而言可能很清楚,但對其他人未必如此。你不能假設別的程序員和你一樣清楚運算符的優先級。 if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT
10.5.3 條件運算符"?"前的表達式(Expressions before ´?´ in the Conditional Operator) 假如一個包含二元運算符的表達式出現在三元運算符" ? : "的"?"之前,那么應該給表達式添上一對圓括號。例如: (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 * * 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 { /* A class implementation comment can go here. */
/** 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;