Java Programming specification

Source: Internet
Author: User

Naming conventions

The purpose of defining this specification is to make all documents in a project look like one person, increasing readability and reducing the loss of the project team due to substitutions. (These specifications do not have to be absolutely adhered to, but make sure that the program is readable)

Naming of the package
The package name should be made up of a lowercase word.

Name of Class
Class names must be made up of uppercase letters and other lowercase words.

Name of Class variable
The name of the variable must begin with a lowercase letter. The following words start with capital letters.

Name of the Static Final variable
The name of the Static Final variable should be capitalized and indicate the full meaning.

Name of the parameter
The name of the parameter must be the same as the variable's naming convention.

Naming the array
Arrays should always be named in the following way:

byte[] buffer; Instead of: Byte buffer[];

Parameters of the method
Use meaningful parameters to name them, and, if possible, use the same names as the fields to be assigned:

Setcounter (int size) {
this.size = size;
}

Java File Styles

All Java (*.java) files must adhere to the following style rules

Copyright information
The copyright information must be at the beginning of the Java file, such as:

/**
* copyright®2000 Shanghai XXX Co. Ltd.
* All right reserved.
*/

Other information that does not need to appear in Javadoc can also be included here.

Package/imports
Before the package line is to be import, the standard package name in import is preceded by the local pack name and is sorted alphabetically. If the import row contains a different subdirectory in the same package, it should be handled with *.

Package hotlava.net.stats;

Import java.io.*;
Import java.util.Observable;
Import hotlava.util.Application;

Here java.io.* used instead of InputStream and OutputStream.

Class
The next is the comment of the class, which is usually used to interpret the class.

/**
* A class representing a set of packet and byte counters
* It is observable-allow it to be watched
* Reports changes when the current set was complete
*/

Next is the class definition, which contains the extends and implements of the different rows.

public class CounterSet
Extends Observable
Implements Cloneable

Class fields
Next is the member variable for the class:

/**
* Packet Counters
*/
protected int[] packets;

The member variable for public must generate a document (JAVADOC). Member variables defined by the proceted, private, and package can have no comment if the name has a clear meaning.

Access method
Next is the method of accessing the class variable. It is simply used to get the value of the class variable assignment, which can be simply written on one line.

/**
* Get the counters
* @return An array containing the statistical data. This array has been
* Freshly allocated and can is modified by the caller.
*/
Public int[] Getpackets () {return Copyarray (packets, offset);}
Public int[] GetBytes () {return Copyarray (bytes, offset);}

Public int[] Getpackets () {return packets;}
public void Setpackets (int[] packets) {this.packets = packets;}

Other methods do not write on a line

constructor function

Next is the constructor, which should be written in an incremental way (for example: many of the arguments are written in the back).
The type of access ("public", "private", etc.) and any "static", "final" or "synchronized" should be on one line, and the methods and parameters are written in another line, which makes the methods and parameters easier to read.

Public
CounterSet (int size) {
this.size = size;
}

Cloning method
If this class can be cloned, then the next step is the Clone method:

Public
Object Clone () {
try {
CounterSet obj = (counterset) super.clone ();
Obj.packets = (int[]) packets.clone ();
obj.size = size;
return obj;
}catch (Clonenotsupportedexception e) {
throw new Internalerror ("Unexpected clonenotsupportedexception:" + e.getmessage ());
}
}

Class method
Here's how to start writing classes:

/**
* Set the packet counters
* (such as when restoring from a database)
*/
Protected final
void SetArray (int[] R1, int[] R2, int[] R3, int[] R4)
Throws IllegalArgumentException
{
//
Ensure the arrays is of equal size
//
if (r1.length! = R2.length | | r1.length! = R3.LENGTH | | r1.length! = r4.length)
throw new IllegalArgumentException ("Arrays must be of the same size");
System.arraycopy (R1, 0, R3, 0, R1.length);
System.arraycopy (R2, 0, R4, 0, r1.length);
}

ToString method
In any case, each class should define the ToString method:

Public
String toString () {
String retval = "CounterSet:";
for (int i = 0; i < data.length (); i++) {
retval + = data.bytes.toString ();
retval + = data.packets.toString ();
}
return retval;
}
}

Main method
If the main (string[]) method is already defined, it should be written at the bottom of the class.

Code writing format

Code style
The code should be in UNIX format, not Windows (e.g., carriage return to carriage return + line break)
Documentation
You must use Javadoc to generate a document for the class. Not only is it a standard, it is also a method that is recognized by various Java compilers. It is not recommended to use @author tags because the code should not be personally owned.
Indent in
The indentation should be 2 spaces per line. Do not save the tab character in the source file. When you use different source control tools, the tab character expands to a different width because of different user settings.
If you use Ultredit as your Java source editor, you can prevent the tab character from being saved by setting the tab length Room 2 spaces in Ultredit, and then using the format| The Tabs to Spaces menu converts the Tab to a space.
Page width
The page width should be set to 80 characters. The source code generally does not exceed this width and results in a full display, but this setting can also be flexibly adjusted. In any case, an extra-long statement should be wrapped around a comma or an operator. When a statement is wrapped, it should be indented 2 characters longer than the original statement.
{} pair
The statement in {} should be a single line. For example, the 1th line below is wrong and the 2nd line is correct:

if (i>0) {i + +}; Error, {and} on the same line

if (i>0) {
i + +
}; Correct, {separate as a row
} statement is always a single line.

If the} statement should be indented to a position relative to its corresponding {that line.

Brackets
There should be no space between the opening parenthesis and the next character, nor should there be a space between the closing parenthesis and the previous character. The following example illustrates the error and correct use of parentheses and spaces:

Callproc (Aparameter); Error
Callproc (Aparameter); That's right

Do not use meaningless parentheses in the statement. Parentheses should only appear in the source code for some purpose. The following example shows the error and correct usage: if ((I) = 42) {//error-parenthesis meaningless
if (I = =) or (J = =) then//correct-it does require parentheses

Program Writing Specification

Exit ()
Exit should not be called except in main where it can be called. Because doing so does not give any code code the opportunity to intercept the exit. A similar background service program should not be exited because a library module decides to exit.
Abnormal
The declared error should throw a runtimeexception or derived exception.
The top-level main () function should intercept all exceptions and print (or record in the log) on the screen.
Garbage collection
Java uses sophisticated background garbage collection techniques instead of reference counting. However, this can cause a problem: You must clear the object after you have finished using the instance. For example, a Prel programmer might write:
...
{
FileOutputStream fos = new FileOutputStream (projectfile);
Project.save (FOS, "IDE Project File");
}
...

Unless the output stream is closed out of scope, the non-reference count programming language, such as Java, is not automatically completed for the variable to clear the work. Must be written as follows:

FileOutputStream fos = new FileOutputStream (projectfile);
Project.save (FOS, "IDE Project File");
Fos.close ();
Clone

The following is a useful method: &NBSP;

implements cloneable 
public 
Object clone ()  
{ 
try { 
ThisClass obj = (thisclass) super.clone ();  
Obj.field1 = (int[]) field1.clone ();  
Obj.field2 = field2; 
return obj; 
} catch (Clonenotsupportedexception e) { 
throw new Internalerror ("Unexpected clonenotsupportedexception:" + e.getmessage ());  
}} 

Final class  
never define a class as final for performance reasons (unless the program's framework requires)  
If a class is not yet ready to be inherited, it is best to note it in the class document instead of defining her as final. This is because no one can guarantee that there will be some reason for inheriting her.  
accesses the member variable   of the class;
most of the class member variables should be defined as protected to prevent inheriting classes from using them.  
Note that you want to use "int[] packets" instead of "int packets[]", and never use the latter. &NBSP

public void Setpackets (int[] packets) {this.packets = packets;}  

CounterSet (int size)  
{ 
This.size = size; 
} 

Programming Tips  

byte array to characters 
to convert a byte array to characters, you can do this:  

"Hello world!". GetBytes ();

Utility class
The Utility class (a class that simply provides a method) should be declared abstract to prevent it from being inherited or initialized.

Initialization
The following code is a good way to initialize an array:

objectarguments = new object[] {arguments};

Enum type
JAVA support for enumerations is not good, but the following code is a useful template:

Class Colour {
public static final Colour BLACK = new Colour (0, 0, 0);
public static final Colour RED = new Colour (0xFF, 0, 0);
public static final Colour GREEN = new Colour (0, 0xFF, 0);
public static final Colour BLUE = new Colour (0, 0, 0xFF);
public static final colour white = new Colour (0xFF, 0xFF, 0xFF);
}

This technique allows for constants such as Red, GREEN, BLUE, and so on that can be used like enumeration types in other languages. They can be compared using the = = operator. But there is a flaw in this use: If a user uses this method to create a color BLACK

New Colour (0,0,0)

So this is another object, and the = = operator generates an error. Her equal () method is still valid. For this reason, the flaw in this technique is best documented or used only in your own package.

Swing
Avoid using AWT components
Mixed use of AWT and Swing components
If you want to mix AWT components with Swing components, use them with care. In fact, try not to mix them up for use.

Rolling AWT Components
AWT components should never use the JScrollPane class for scrolling. It is important to use the AWT ScrollPane component to implement the AWT components when rolling.

Avoiding the use of AWT components in Internalframe components
Try not to do so, otherwise there will be unforeseen consequences.

Z-order problems
AWT components are always displayed on top of Swing components. Be careful when using the pop-up menu that contains AWT components, and try not to use it as much as possible.

Debugging

Debugging is a very important part of software development, which exists in various parts of the software life cycle. Debugging can be configured to open, close is the most basic.

A common debugging method is to use a PrintStream class member that is null when no debug flow is defined, and the class defines a debug method to set the stream for debugging.

Performance

When writing code, you should consider performance issues from beginning to finish. This is not to say that time should be wasted on optimizing the code, but that we should always remind ourselves of the efficiency of the Code. For example: If there is no time to implement an efficient algorithm, then we should write it down in the document so that we can implement her later when we have a space.

Not everyone agrees to optimize performance when writing code, and they think that the problem of performance optimization should be considered later in the project, that is, after the outline of the program has been implemented.
Unnecessary construction of objects
Do not construct and dispose of objects in loops

Using the StringBuffer object
To use the StringBuffer class when working with strings, the StringBuffer class is the basis for composing the string class. The String class encapsulates the StringBuffer class, which, at the expense of more time, provides the developer with a secure interface. When we construct a string, we should use StringBuffer to do most of the work, and then convert the StringBuffer object to the desired string object when the work is done. For example, if you have a string that must be continually added after many characters to complete the construction, then we should use the StringBuffer object and her append () method. If we use the String object instead of the StringBuffer object, it will take a lot of unnecessary CPU time to create and dispose of the object.

Avoid too much use of the Synchronized keyword
Avoid unnecessary use of the keyword synchronized, should be used when necessary to use her, this is a good way to avoid deadlocks.

Portability
Borland Jbulider do not like synchronized this keyword, if your breakpoint is set in the scope of these keywords, debugging you will find the breakpoint will be everywhere jump, let you overwhelmed. Try not to use it unless you have to.

Line break
If you need to wrap, try to use println instead of "" in the string.
You don't want this: System.out.print ("hello,world!");
To do this: System.out.println ("hello,world!");

Or you can construct a string with a newline character, at least like this: string newline = System.getproperty ("Line.separator");
System.out.println ("Hello World" + newline);

PrintStream
PrintStream has been deprecated (deprecated), using printwrite to replace her.

Java Programming specification

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.