Good Java Style:part 1

Source: Internet
Author: User
Tags coding standards comments end gettext integer variables variable trim
Good Java Style:part 1
by Thornton Rose

Introduction
Have worked as a software developer and consultant for many years, I have seen a large amount of code in a variety of PR Ogramming languages. It has run the gamut from elegant to ugly, and unfortunately much of it has been. I hope to persuade for you and my fellow developers, which we should give as much attention to the style of our code as we giv E to the user interface and visible parts of a application. In this the "a" a two part series, I explain why we should care about how our code looks and illustrate some Gen eral elements of good Java style.

Why Style Matters
Even though Java is used to write programs rather than, it's prose still to express used and thoughts. And, in addition to conveying information, those thoughts and ideas must do actually. Worrying about good style may seem like a waste for time, but it behooves us to write we code such that thoughts and I Deas It expresses are exceptionally clear.

Here are several reasons for using good style [from "Java Code conventions, Sun Microsystems]:


80% of the lifetime cost of a software product goes to maintenance.
Hardly any software are maintained for it whole life by the original author (s).
Using good style improves the maintainability of software code.
If The source code is shipped with the software, it should being as well-packaged, clean, and professional as the rest of the Product.

Writing code with good style also provides the following benefits:


It improves the readability, consistency, and homogeneity of the code, which makes it easier to understand and maintain.
It makes the code easier to trace and debug, because it ' s clear and consistent.
It allows to continue more easily where and another programmer stopped after a long particularly of time.
It increases the benefit of the code walkthroughs, because the participants can focus more on what the ' code is doing.

General guidelines
Writing Java with good style isn't hard, but it does require attention to detail. Here are some general guidelines to follow:


Make the code clear and easy to read.
Make the code consistent.
Use obvious identifier names.
Logically organize your files and classes.
Have only one class per file (not including inner classes).
Use a maximum line width of 80-90 characters.
Use whitespace and/or the other separators judiciously.
Use spaces instead of the tabs for indentation.

Tabs vs. spaces
Tabs vs. Spaces is one of the several religious issues related to writing code, and I am not suggesting Right way. I espouse using spaces because it ensures that my code would look the same in my editor as it does in your editor and Vice Versa. If you feel the using spaces instead of tabs "just ain ' t right", then by the all means use tabs.

Braces and indentation
Indent style (cf., Raymond, "Indent style"), or the placement of braces ("{" and "}") and the associated indentation of CO De, are another of the religious issues related to writing code. There are several indent styles common to C-style "like Java" and I am not languages to going this one of suggest is S Uperior. In most of the "example code in" article, I use what are usually referred to as K&r style. If you don ' t like K&r, by the all means use another style.

Comments
There are two type of comments that I can put in your Java Code:javadoc comments (also called documentation comments) a ND implementation comments. Javadoc comments can is extracted by the Javadoc tool to produce API documentation. Implementation comments are those comments that explain the and why of the code. Use the following guidelines for commenting your Java code:


Use Javadoc comments wherever they are allowed (in classes and methods at minimum).
Use blocks comments rather than end-of-line/trailing comments, except in special cases, such as variable.

Also, keep in mind that good comments are helpful; Bad comments are a nuisance.

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 for writing blocks and statements:


Put only one statement each line.
Always use braces with control statements (e.g., ' if ').
Consider marking the end of a blocks with a comment (e.g.,}//End If), particularly with long or nested blocks.
Put variable declarations in the beginning of a block.
Always Initialize variables.
If you are want to be a perfectionist, left-align variable names.
Indent the case clauses in a switch block.
Put whitespace before and after operators.
In if, as, or while, put whitespace before the "(".
Use whitespace and parentheses into expressions to increase readability.

Variables used in "for" loops are the exception to putting Variables at the beginning of a. The loop variable (s) May is declared in the initialization part of the for statement, e.g., for (int i = 0;.)

.

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 for you nearly crazy.

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


Related Links

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 (known in print as the New Hacker ' s Dictionary), Eric S. Raymond.
Indent Style, the Jargon File, Eric S. Raymond.

References

Java Code Conventions. Copyright) 1995-2000 Sun Microsystems, Inc.

About the Author
Thornton Rose are a contract software developer in Atlanta, Ga. He can be reached via e-mail at thornton.rose@mindspring.com.






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.