http://www.developer.com/java/other/article.php/600581/Good-Java-Style-Part-1.htm
Having worked as a software developer and consultant for many years, I have seen a large amount of code in a variety of programming languages. It has run the gamut from elegant to ugly, and unfortunately much of it has been ugly. I hope to persuade you, and my fellow developers, that we should give as much attention to the style of our code as we give to the user interface and other visible parts of an application. In this the first part of a two part series, I explain why we should care about how our code looks and illustrate some general elements of good Java style. Even though Java is used to write programs rather than prose, it is still used to express thoughts and ideas. And, in addition to conveying information, those thoughts and ideas must actually do something. Worrying about good style may seem like a waste of time, but it behooves us to write our code such that the thoughts and ideas it expresses are exceptionally clear. Here are several reasons for using good style [from "Java Code Conventions," Sun Microsystems]: Writing code with good style also provides the following benefits: Writing Java with good style is not hard, but it does require attention to detail. Here are some general guidelines to follow: Tabs vs. spaces is one of several religious issues related to writing code, and I am not suggesting that there is only one right way. I espouse using spaces because it ensures that my code will look the same in my editor as it does in your editor and vice versa. If you feel that using spaces instead of tabs "just ain't right", then by all means use tabs. Indent style (cf., Raymond, "Indent Style"), or the placement of braces ("{" and "}") and the associated indentation of code, is another of the religious issues related to writing code. There are several indent styles common to C-style languages like Java, and I am not going to suggest that one of them is superior. In most of the example code in this article, I use what is usually referred to as K&R style. If you don't like K&R, by all means use another style. There are two type of comments that you can put in your Java code: Javadoc comments (also called documentation comments) and implementation comments. Javadoc comments can be extracted by the javadoc tool to produce API documentation. Implementation comments are those comments that explain the how and why of the code. Use the following guidelines for commenting your Java code: Also, keep in mind that good comments are helpful; bad comments are a nuisance. Example 1. Bad Comment Style Example 2. Good Comment Style. Use the following guidelines for writing blocks and statements: Variables used in 'for' loops are the exception to putting variables at the beginning of a block. The loop variable(s) may be declared in the initialization part of the for statement, e.g., for Putting a comment at the end of a block can help you track down accidentally deleted closing braces. Finding those in a large source file can sometimes drive you nearly crazy. Example 3. Bad Block Style. Example 4. Good Block Style. Thornton Rose is a contract software developer in Atlanta, Ga. He can be reached via e-mail at thornton.rose@mindspring.com.
Good Java Style: Part 1
February 22, 2001
Introduction
Why Style Matters
General Guidelines
Tabs vs. Spaces
Braces and Indentation
Comments
// 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);
}
}
Blocks and Statements
. (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;
else:
freakOut();
} // end switch
} catch(Exception ex) {
...
} // end try
Related Links
References
Java Code Conventions. Copyright ) 1995-2000 Sun Microsystems, Inc.
About the Author