Introduced
As a software developer and consultant who has worked for many years, I have seen a lot of different programming language code. There are both elegant and ugly, but unfortunately most of them are ugly. I want to be able to convince you, my development partners, that we should pay enough attention to our code style, especially those that provide user interface and other visual parts in the application. In the first part of the two-part series, I'll explain why we should care about the appearance of our code and then explain some of the general elements of a good Java style.
Why the code is important
Although Java is used to write programs rather than prose, it is still used to express ideas and opinions. And, as the survey shows, those ideas and ideas have done a lot of things in practice. Worrying about writing a good Java style seems like a waste of time, but in fact it is appropriate for us to write a program, because the ideas and ideas it wants to express are exceptionally clear.
Here are some reasons why you should use a good Java code specification
80% of the lifetime of a software product is in maintenance (maintenance).
Almost none of the software has been maintained by its authors throughout its lifetime.
The use of good style improves the maintainability of the software.
If the source code and software products are bundled to the customer, as the rest of the product, it should have good subcontracting (well-packaged), clear enough and professional code.
There are several benefits to writing code with a good style:
Improve the readability, consistency and harmony of the code. These can make the code easier to understand and maintain.
Makes the code easier to track and debug because it is clear and persistent.
Makes it easier for you or another programmer to continue writing at the end, especially after a long time.
Increases the benefits of code walkthroughs because it allows participants to focus more on what the code is doing.
Summary policy
It's not difficult to use a good Java style, but it does require attention to detail. Here are some common guidelines for outlining:
Make the code clearer and easier to read
Make code more persistent
Use the obvious identifier name
Logically organize your files and classes
Each file has only one class (not including some internal classes here)
Use maximum line width of 80-90 characters
Wisely use spaces to and/or other delimiters
On the indentation, use space (spaces) to replace the tab
tabs vs. spaces
When writing code, "Tabs vs. Space" is a rigorous point of view. I am not implying that there is only one right way. I support using spaces because it guarantees that my code will look the same in your editor as it does in my editor, and vice versa. If you feel the use of a space instead of tab "is not correct", then use the tab bar.
Brackets and indents
The indentation style (cf., Raymond, "Indent style"), or the placement of parentheses ("{" and "}") and some associated indentation codes, is another rigorous point of view when writing code. Like Java, there are many C-style languages in existence. I'm not suggesting either one of them is a better priority. In most examples of this article, I use the k&r style, and if you don't like the K&r style, use a different style.
Note
In Java code you can use two kinds of annotations: Javadoc annotations (also known as document annotations) and executive comments. Javadoc annotations can be decompressed by the Javadoc tool to create an API document. Execution comments are comments that explain the purpose and manner of the Code. When commenting on your Java code, use the following guidelines:
Use Javadoc annotations as much as possible (on classes and methods to minimize them).
Use block annotation, less use//annotation, unless some special case, such as variable declaration
Remember: Good notes are helpful, bad notes 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 * *
Exceptiondialog.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 ' 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) {
The exception to the user.
Exceptiondialog.show (This, "Invalid rotation length:", ex);
}
}
Blocks and statements
Use the following guidelines to write blocks and statements:
A line only writes one statement
The control statement always uses parentheses such as {} (e.g., ' if ').
Consider using a comment at the end of the block (e.g.,}//ends if), especially long or nested blocks
Place the declaration statement of the variable at the beginning of the block
Always remember to initialize variables
If you're a perfectionist, left-aligned variable names
Indent the case clause in the switch block
Leave blank after operator
In the IF, for, or while statement, leave a blank before the parenthesis "(")
Use whitespace and insertions 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., for (int i = 0; ...).
Inserting a comment at the end of a block helps you inadvertently trace to the closing parenthesis "}" that is deleted.
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