Good Java style (Part 1)
By Thornton rose
Introduction
As a software developer and consultant who has been working for many years, I have seen a lot of diverse programming language code. There are elegant and ugly ones, but unfortunately most of the Code is ugly. I hope to convince you that our development partners should pay enough attention to our code style, especially the code that provides user interfaces and other visualizations in applications. In the first part of the two series, I will explain why we should be concerned about the appearance of our code, and then explain some general elements of a good Java style.
Why is code important?
Although Java is used to write programs rather than prose, it is still used to express ideas and opinions. In addition, the investigation shows that those ideas and opinions have completed many things in reality. Worrying about writing a good Java style seems to be a waste of time, but in fact it is very suitable for us to write programs, because the ideas and opinions it wants to express are exceptionally clear.
Here are some reasons for using good Java code specifications.
- 80% of the lifetime of a software product is under maintenance (maintenance ).
- Almost no software is maintained by its authors throughout its life cycle.
- A good style improves the maintainability of the software.
- If the source code and software products are bundled with the customer, as part of the product, it should have good subcontracting (well-packaged), clear enough and professional code.
Writing code in a good style has the following advantages:
- This improves code readability, continuity, and harmony. This makes the code easier to understand and maintain.
- Make the code easier to trace and debug because it is clear and continuous.
- It makes it easier for you or another programmer to stop writing, especially after a long time.
- Added the benefits of code pre-arrangement (throughs), because it allows the participants to focus more on what the code is doing.
Overview
It is not difficult to use a good Java style, but it must pay attention to the details. Below are some common summary guidelines:
- Make the code clearer and easier to read
- Make code more persistent
- Use an obvious identifier name
- Logically organize your files and Classes
- Each file has only one class (some internal classes are not included here)
- Maximum width of a string of 80 to 90 characters
- Use spaces wisely to separate and/or other separators
- Use space instead of tab.
Tabs vs. Space
When writing code, "tabs vs. Space" is a rigorous viewpoint. Here I am not suggesting that there is only one correct method. I support space, because it ensures that my code is the same in your editor as in my editor, and vice versa. If you feel that it is "Incorrect" to replace tab with spaces, use tab.
Parentheses and indentation
Indentation style (Cf ., raymond, "indent style"), or place parentheses ("{" and "}") and some associated indent code, is another rigorous point of view. Like java, many c-style languages exist. I am not suggesting which of them has a higher priority or a better one. In most of the sample code in this article, I use the K & R style. If you do not like the K & R style, use other styles.
Note
In Java code, you can use two types of Annotations: javadoc annotation (also known as document annotation) and execution annotation. Javadoc annotations can be decompressed by javadoc tools to create an API document. The comments executed are comments that explain the purpose and method of the Code. Use the following guidelines when commenting on your Java code:
- Use javadoc annotations as much as possible (to minimize the number of classes and methods ).
- Use block comments more and less // comments unless otherwise specified, such as variable Declaration
Remember: good comments are helpful, and bad comments are troublesome.
Example 1. Bad comment Style
// 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 */
Predictiondialog. Show (this, "invalid rotation length:", ex );}
}
Example 2. Good comment Style
/**
* 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
* 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.
Predictiondialog. Show (this, "invalid rotation length:", ex );
}
}
Blocks and statements
Use the following guidelines to compile blocks and statements:
- Write only one statement in one row
- The control statement always uses parentheses such as {} (e.g., 'if ').
- Consider using a comment (e.g.,} // end if) at the end of the block, especially long or nested blocks.
- Statement for placing variables at the beginning of a block
- Always remember to initialize the variable
- If you are a perfectionist, left-aligned variable names
- Indent the case clause in the switch block
- Leave blank behind the operator
- In the if, for, or while statement, leave blank before the brackets "("
- Use blank space and insertion in expressions to enhance readability
The variable in the for loop is an exception. Loop variables may be defined in the statement initialization section. E.g.,
.
Inserting a comment at the end of the block helps you accidentally track the deleted ending bracket "}".
Example 3. Bad block style.
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 ){...}
Example 4. Good block style.
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
Translated by willpower, 2003.11.17