 |
建站必读 |
 |
|
|
 |
|
 |
|
| |
| 当前位置:首页 -> 建站必读 -> JSP技术 |
|
Good Java Style: Part 2 |
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 more elements of good style and bring my case to a conclusion.
Source Files
There are many ways that a Java source file can be organized. Here is one that works well:
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 for 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 you prefer to import individual classes 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 that do not have obvious names. Use end-of-line comments, or put a comment at the beginning of the section. Also, if you really want to be 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.*;   |
| |
|
| |
本站关键词: |
|
|
|
|
 |
|
 |
|