Good Java Style:part 2

Source: Internet
Author: User
Tags coding standards comments final header variables return string version
Good Java Style:part 2
by Thornton Rose

Introduction
This is the conclusion of a Two-part series on Java coding style. In good Java Style:part 1

, I introduced my case for writing Java code using good habits, explained why we should care about the way our code looks, and illustrated some general elements of good Java style. In this part, I illustrate the more elements of good style and bring me case to a conclusion.

Source Files
There are many ways that a Java source file can is organized. This is one this works:


File Header Comment (optional).
Package declaration.
Blank line or other separator.
Import statements.
Blank line or other separator.
Class (es).

Example 1. Bad File organization.


Package org.rotpad;
Import java.awt.*;
Import javax.swing.event.*;
Import org.javacogs.*;
Import javax.swing.*;
Import java.awt.event.*;
Class Foo {
...
}
public class Rotpad extends JFrame {
...
}


Example 2. Good File organization.


Package org.rotpad;

Java classes
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Import javax.swing.event.*;

Javacogs classes
Import org.javacogs.*;

/**
* Rotpad is a simple GUI application to performing rotation ciphers on plain
* Text.
*
* @author Thornton Rose
* @version 1.0
*/
public class Rotpad extends JFrame {
...
}

//-----------------------------------------------------------------------------

/**
* Foo is ...
*
* @author Thornton Rose
* @version 1.0
*/
Class Foo {
...
}


Import statements
A complex class can have a large number of imports, which can get unruly, especially if your prefer to import individual CL Asses instead of whole packages (e.g., java.awt.*). To get a handle on imports, organize them as follows:


Java standard classes (java.*).
Java extension Classes (javax.*).
Third-party classes.
Application classes.

Be sure to comment the Third-party and application classes, particularly those this do not have obvious. Use end-of-line comments, or put a comment in the beginning of the section. Also, if you are really want to being a perfectionist, order each group of imports alphabetically.

Example 3. Bad Import Style.


Import java.util.*;
Import javax.swing.*;
Import java.awt.event*;
Import com.gensym.com.*;
Import javax.swing.table.*;
Import com.pv.jfcx.*;
Import java.awt.*;
Import com.melthorn.util.*;


Example 4a. Good Import Style.


Import java.awt.*;
Import java.awt.event*;
Import java.util.*;
Import javax.swing.table.*;
Import com.gensym.com.*; Beanxporter
Import com.pv.jfcx.*; Protoview
Import com.melthorn.util.*; Utilities

Example 4b. Good Import Style.



Java classes
Import java.awt.*;
Import java.awt.event*;
Import java.util.*;
Import javax.swing.table.*;

Beanxporter
Import com.gensym.com.*;

Protoview GUI Components
Import com.pv.jfcx.*;

Application Classes
Import com.melthorn.util.*;


Classes
Organizing a Java source file without organizing the classes in it would not gain to you the most in the way of proper style. Here's how to organize the classes in your source files:


Javadoc Comment or other header comment.
Class declaration.
Field declarations.
Blank line or other separator.
Constructors.
Blank line or other separator.
Methods, except main ()

, grouped logically.
Blank line or other separator.
Inner classes.
Blank line or other separator.
Main ()

.

Example 5. Bad Class Style.


Rotpad-GUI app. For ROT ciphering
public class Rotpad extends JFrame {
private static final String transform_rot13 = "ROT13";
private static final String transform_rot13n5 = "Rot13n5";
private static final String Transform_rotascii = "Rot-ascii";

private void Jbinit () throws Exception {
...
}

public static final String TITLE = "Rotpad";
public static final String VERSION = "1.0";

public static void Main (string[] args) {
...
}

Public Rotpad () {
...
}

Private JPanel JPanel1 = new JPanel ();
Private JPanel JPanel2 = new JPanel ();
Private BorderLayout borderLayout1 = new BorderLayout ();
...
}


Example 6. Good Class Style.


/**
* Rotpad is a simple GUI application to performing rotation ciphers on plain
* Text.
*
* @author Thornton Rose
* @version 1.0
*/
public class Rotpad extends JFrame {
Public constants

public static final String TITLE = "Rotpad";
public static final String VERSION = "1.0";

Private Constants

private static final String transform_rot13 = "ROT13";
private static final String transform_rot13n5 = "Rot13n5";
private static final String Transform_rotascii = "Rot-ascii";

GUI components [JBuilder generated]

Private BorderLayout borderLayout1 = new BorderLayout ();
Private JPanel JPanel1 = new JPanel ();
Private JPanel JPanel2 = new JPanel ();
...

/**
* Construct a new instance of this class.
*/
Public Rotpad () {
...
}

/**
* Initialize UI components. [JBuilder generated]
*/
private void Jbinit () throws Exception {
...
}

...

//--------------------------------------------------------------------------

/**
* Start the application.
*/
public static void Main (string[] args) {
...
}
}


Field Declarations
Some classes have a large number of fields, which can become difficult to maintain if they-not are. Organize them as follows:


Public contstants (final and static final).
Public variables.
Protected constants.
Protected variables.
Package constants.
Package variables.
Private constants.
Private variables.

Additionally, use the following guidelines for writing field declarations:


Use one declaration/line.
Use Javadoc comments in public and protected fields, at minimum.
Use uppercase for the names of constants. Using uppercase makes them much more obvious in both declarations and expressions.
If Use a tool that generates field declarations, such as JBuilder or Visual Cafe, keep the generated fields F Rom the other fields. It makes maintenance of the UI code much easier.

Example 7. Bad Field Style.


public class Customersearchdialog extends JDialog {
Private JLabel firstNameLabel = new JLabel ();
Private JLabel Lastnamelabel = new JLabel ();
public static Final result_select = 1;
Private vector results = new vector (); Search results.
Private DefaultTableModel TableModel = new DefaultTableModel ();
public static Final result_cancel = 0;
// ...
}


Example 8. Good Field Style.


/**
* ...
*/
public class Customersearchdialog extends JDialog {
/**
* Indicates that search was cancelled; Returned by ShowDialog ()
* User clicks Cancel button.
*/
public static Final result_cancel = 0;

/**
* Indicates that a customer is selected; Returned by ShowDialog ()
* User clicks Select button.
*/
public static Final result_select = 1;

Private vector results = new vector (); Search results.
Private DefaultTableModel TableModel = new DefaultTableModel (); Grid model.

GUI fields. [JBuilder]

Private JLabel firstNameLabel = new JLabel ();
Private JLabel Lastnamelabel = new JLabel ();
// ...
}


Method Declarations
Use the following guidelines to writing method declarations:


Always have a Javadoc comment or some other header comment.
Always put the access modifier.
If the line is too long, break it to one or more lines.
If The method is has more than a few parameters, consider putting all on a separate line.
Don ' t put whitespace between the method name and the opening parenthesis ("(").
Always put whitespace (which could is a line break) between the closing parenthesis (")") and the opening brace ("{").

Example 9. Bad method Style.


public int Gettypecount (String custtype)
{
...
}
static public getinstance () {...};
public void Showrange ()
Throws Rangeexception {
...
}


Example 10. Good method Styles.


/**
* Return the ' Single instance ' of this class.
*/
public static Calculationengine getinstance () {
return instance;
}

/**
* Calculate the consumption coefficient.
*/
public float calculateconsumptioncoefficient (int base, float variance,
int iterations) throws Rangeexception {
// ...
}

/**
* Calculate the consumption coefficient.
*/
Public float calculateconsumptioncoefficient (
int base,
Float Variance,
int iterations)
Throws Rangeexception
{
// ...
}

/**
* Calculate the consumption coefficient.
*/
public float calculateconsumptioncoefficient (int base,
Float Variance,
int iterations)
Throws Rangeexception
{
// ...
}


Conclusion
In conclusion, I have one final thought for your on the subject of code style. No matter what guidelines you follow, and no matter how fervent your the about beliefs like things style (cf., indent, "Indent Style"), remember that is you write code your overall goal should is to make the code understandable and Mainta Inable by someone else.

Related Links

Indent Style, the Jargon File, Eric S. Raymond.
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.

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.




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.