身為資深軟體開發者與顧問,我閱讀過大量各類程式語言撰寫的程式碼,風格從優雅到凌亂不一。遺憾的是,大多數程式碼都屬於後者。我希望說服各位開發者,程式碼的風格與使用者介面同樣重要。本系列分為兩部分,第一部分將闡述為何應重視程式碼外觀,並說明良好 Java 風格的一般要素。
Java 雖用於撰寫程式而非散文,但同樣用於表達思想與邏輯。這些思想不僅需傳達資訊,更必須能正確執行。雖然追求良好風格看似耗時,但我們應撰寫出表達清晰、意圖明確的程式碼。
根據 Sun Microsystems《Java Code Conventions》指出:
撰寫良好風格的程式碼還有以下效益:
良好的 Java 風格不難,但需注重細節:
這是程式設計界的「宗教戰爭」之一。我偏好空白,因能確保程式碼在不同編輯器中外觀一致。若你堅持使用 Tab,請自便。
縮排風格(如 K&R 風格)同屬宗教議題,本文範例多採 K&R 風格,讀者可依偏好調整。
Java 註解分為 Javadoc 註解(文件註解)與實作註解。Javadoc 可由工具提取生成 API 文件;實作註解解釋程式碼的如何與為何。建議:
// 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);
}
}
/**
* 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; ...))。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){ ... }
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
Thornton Rose 是亞特蘭大的合約軟體開發者,可透過 thornton.rose@mindspring.com 聯繫。