首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

優良 Java 程式碼風格指南(上)

     編輯:Java 相關知識

前言

身為資深軟體開發者與顧問,我閱讀過大量各類程式語言撰寫的程式碼,風格從優雅到凌亂不一。遺憾的是,大多數程式碼都屬於後者。我希望說服各位開發者,程式碼的風格與使用者介面同樣重要。本系列分為兩部分,第一部分將闡述為何應重視程式碼外觀,並說明良好 Java 風格的一般要素。

為何風格至關重要

Java 雖用於撰寫程式而非散文,但同樣用於表達思想與邏輯。這些思想不僅需傳達資訊,更必須能正確執行。雖然追求良好風格看似耗時,但我們應撰寫出表達清晰、意圖明確的程式碼。

根據 Sun Microsystems《Java Code Conventions》指出:

  • 軟體產品 80% 的生命週期成本用於維護。
  • 幾乎沒有軟體由原作者維護到底。
  • 良好風格能提升程式碼可維護性。
  • 若原始碼隨產品出貨,應如同產品其他部分般專業、整潔。

撰寫良好風格的程式碼還有以下效益:

  • 提升可讀性、一致性與同質性,易於理解與維護。
  • 便於追蹤與除錯,因結構清晰一致。
  • 方便接手他人或自己久未碰觸的程式碼。
  • 程式碼走讀時,參與者能更專注於邏輯而非格式。

一般準則

良好的 Java 風格不難,但需注重細節:

  • 使程式碼清晰易讀。
  • 保持一致性。
  • 使用顯而易見的識別名稱。
  • 邏輯性地組織檔案與類別。
  • 每個檔案僅包含一個類別(內部類別除外)。
  • 行寬限制在 80-90 字元。
  • 善用空白與分隔符。
  • 縮排使用空白而非 Tab。

Tab v.s. 空白

這是程式設計界的「宗教戰爭」之一。我偏好空白,因能確保程式碼在不同編輯器中外觀一致。若你堅持使用 Tab,請自便。

大括號與縮排

縮排風格(如 K&R 風格)同屬宗教議題,本文範例多採 K&R 風格,讀者可依偏好調整。

註解規範

Java 註解分為 Javadoc 註解(文件註解)與實作註解。Javadoc 可由工具提取生成 API 文件;實作註解解釋程式碼的如何與為何。建議:

  • 在所有允許處使用 Javadoc 註解(至少類別與方法)。
  • 優先使用區塊註解,僅在變數宣告等特殊情況使用行尾註解。
  • 好的註解助人,壞的註解添亂。

範例 1:不良註解風格

// applyRotAscii() -- Apply ASCII ROT
private void applyRotAscii(){
    try{
        int rotLength = Integer.parseInt(rotationLengthField.getText().trim()); // get rot len
        RotAscii cipher = new RotAscii(rotLength); // new cipher
        textArea.setText(cipher.transform(textArea.getText())); // transform
    }catch(Exception ex){
        /* Show exception */
        ExceptionDialog.show(this, "Invalid rotation length: ", ex);
    }
}

範例 2:良好註解風格

/**
 * Apply the ASCII rotation cipher to the user's text. The length is retrieved
 * from the rotation length field, and the user's text is retrieved from the
 * text area.
 *
 * @author Thornton Rose
 */
private void applyRotAscii() {
    int rotLength = 0; // rotation length
    RotAscii cipher = null; // ASCII rotation cipher
    try {
        // Get rotation length field and convert to integer.
        rotLength = Integer.parseInt(rotationLengthField.getText().trim());
        // Create ASCII rotation cipher and transform the user's text with it.
        cipher = new RotAscii(rotLength);
        textArea.setText(cipher.transform(textArea.getText()));
    } catch(Exception ex) {
        // Report the exception to the user.
        ExceptionDialog.show(this, "Invalid rotation length: ", ex);
    }
}

區塊與陳述句

  • 每行僅一個陳述句。
  • 控制陳述句(如 if)務必加大括號。
  • 長或巢狀區塊結尾建議加註解(如 } // end if)。
  • 變數宣告置於區塊開頭。
  • 變數必須初始化。
  • 追求完美者可左對齊變數名稱。
  • switch 區塊的 case 條款需縮排。
  • 運算子前後加空白。
  • if、for、while 的左括號前加空白。
  • 善用空白與括號提升可讀性。
  • for 迴圈變數可宣告於初始化區(如 for (int i = 0; ...))。
  • 區塊結尾加註解有助追蹤遺漏的右大括號。

範例 3:不良區塊風格

try{
    for(int i=0;i<5;i++){
        ...
    }
    int threshold=calculateThreshold();
    float variance=(threshold*2.8)-1;
    int c=0;
    if (threshold<=15) c=calculateCoefficient();
    switch(c){
        case 1: setCeiling(c*2); break;
        case 2: setCeiling(c*3); break;
        else: freakOut();
    }
}catch(Exception ex){ ... }

範例 4:良好區塊風格

try {
    int threshold = 0;
    float variance = 0.0;
    int coefficient = 0;
    // Prepare 5 cycles.
    for (int i = 0; i < 5; i ++) {
        prepareCycle(i);
    }
    // Calculate the threshold and variance.
    threshold = calculateThreshold();
    variance = (threshold * 2.8) - 1;
    // If the threshold is less than the maximum, calculate the coefficient.
    // Otherwise, throw an exception.
    if (threshold <= MAX_THRESHOLD) {
        coefficient = calculateCoefficient();
    } else {
        throw new RuntimeException("Threshold exceeded!");
    }
    // Set the ceiling based on the coefficient.
    switch (coefficient) {
        case 1:
            setCeiling(coefficient * 2);
            break;
        case 2:
            setCeiling(coefficient * 3);
            break;
        default:
            freakOut();
    } // end switch
} catch(Exception ex) {
    ...
} // end try

相關連結

  • Tabs vs. Spaces, Jamie Zawinski
  • Writing Robust Java Code — The Ambysoft Inc. Coding Standards for Java, Scott Ambler
  • Draft Java Coding Standard, Doug Lea
  • Java Code Conventions, Sun Microsystems, Inc.
  • How to Write Doc Comments for Javadoc, Sun Microsystems, Inc.
  • The Jargon File, Eric S. Raymond
  • Indent Style, The Jargon File, Eric S. Raymond

作者簡介

Thornton Rose 是亞特蘭大的合約軟體開發者,可透過 thornton.rose@mindspring.com 聯繫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved