注意:空格不應該置於方法名與其左括弧之間。這將有助於區分關鍵字和方法調用。 - 空白應該位於參數列表中逗號的後面 - 所有的二元運算符,除了".",應該使用空格將之與操作數分開。一元操作符和操作數之間不因該加空格,比如:負號("-")、自增("++")和自減("--")。例如: a += c + d; a = (a + b) / (c * d);
while (d++ = s++) { n++; } printSize("size is " + foo + "\n");
不要使用內嵌(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;