Java code specification

Source: Internet
Author: User
Java code specifications-general Linux technology-Linux programming and kernel information. For more information, see the following. All program development manuals contain various rules. Some freelancers may be uncomfortable with these rules.
Yes, but these rules are required when multiple developers write together. This is not just to open
Efficiency, but also for later maintenance.

Naming rules
The purpose of defining this specification is to make all documents in the Project look as written by one person, increasing readability and reducing
The loss caused by substitution in the project team. (These specifications do not always comply with, but must
Program has good readability)


Package name
The Package name must be a lowercase word.
Class Name
The Class name must start with an upper-case letter, and all other letters must be lowercase words.
Class variable name
The variable name must start with a lowercase letter. The following words start with an uppercase letter.
Static Final variable name
The names of Static Final variables should all be in uppercase and indicate the complete meaning.
Parameter Name
The parameter name must be consistent with the variable naming rules.
Array name
Arrays should always be named in the following way:

Byte [] buffer;


Instead:

Byte buffer [];



Method Parameters
Use meaningful parameter names. If possible, use the same name as the field to be assigned values:

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




Java file Style
All Java (*. java) files must comply with the following style rules:


Copyright information
The copyright information must start with a java file, for example:

/**
* 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 imported, the standard package name in the import must be before the local package name, and
In alphabetical order. If the import line contains different subdirectories in the same package, use *
Processing.

Package hotlava.net. stats;

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


Here, java. io. * is used to replace InputStream and OutputStream.


Class
Next is the class annotation, which is generally used to explain the class.

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


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

Public class CounterSet
Extends Observable
Implements Cloneable



Class Fields
The following is the member variable of the class:

/**
* Packet counters
*/
Protected int [] packets;


Public member variables must generate a document (JavaDoc ). Proceted, private, and package Definitions
If the name of a member variable is clear, no comments are provided.


Access Method
Next is the method for accessing class variables. It is simply used to assign values to class variables to get values.
Write a single order on one line.

/**
* Get the counters
* @ Return an array containing the statistical data. This array has been
* Freshly allocated and can be 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 ;}


Do not write other methods on one line


Constructor
The next step is the constructor, which should be written in an incremental manner (for example, a large number of parameters are written later ).
Access type ("public", "private", etc.) and any "static", "final" or "synchronized"
It should be in one row, and the method and parameter should be written in another row, so that the method and parameter can be easier to read.

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



Clone Method
If this class can be cloned, 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
The following describes how to write a class:

/**
* 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 are 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 has been defined, it should be written at the bottom of the class.

Code writing format


Code style
The Code should be in unix format instead of windows (for example, press enter to press ENTER + line feed)
Docized
You must use javadoc to generate documents for classes. Not only because it is a standard, but also by various java compilers
Method. Using @ author flag is not recommended because the code should not be owned by individuals.
Indent
Indentation should contain 2 spaces in each line. Do not save the Tab character in the source file. Use different source code management tools.
The Tab character is extended to different widths because of different settings.
If you use UltrEdit as your Java source code editor, you can disable it by performing the following operations:
Save the Tab character by setting two spaces in the length room of the Tab by using UltrEdit, and then using
Format | Tabs to Spaces convert 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 thus cannot be fully displayed, but this setting
It can also be adjusted flexibly. In any case, extra-long statements should be folded after a comma or an operator.
After a statement is folded, it should be 2 Characters more indented than the original statement.
{} Pair
The statement in {} should be a separate row. For example, the following 1st rows are incorrect, and the 2nd rows are correct:

If (I> 0) {I ++}; // error, {And} are in the same row

If (I> 0 ){
I ++
}; // Correct, {separate row


} The statement is always a single row.


If}, the statement should be indented to the position corresponding to the {Line.


Brackets
There should be no space between the left bracket and the next character. Similarly, there should be no space between the right brace and the previous character.
The following example shows the errors and correct use of parentheses and spaces:

CallProc (AParameter); // Error
CallProc (AParameter); // correct

Do not use meaningless parentheses in statements. parentheses should only appear in the source code for some purpose. Below
The following examples describe errors and correct usage:

If (I) = 42) {// error-Parentheses meaningless
If (I = 42) or (J = 42) then // correct-brackets are required.


Programming Specification


Exit ()
In addition to being called in main, exit should not be called in other places. Because this does not give any code
Code Opportunity to intercept and exit. A program similar to the background service location should not be exited because of a database module.
And then exit.
Exception
The declared error should throw a RuntimeException or a 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 mature background garbage collection technology to replace reference counting. But this will cause a problem: you must
After using the instance of the object, clear the job. For example, a prel programmer may write as follows:

...
{
FileOutputStream fos = new FileOutputStream (projectFile );
Project. save (fos, "IDE Project File ");
}
...


Unless the output stream is closed once it is out of scope, non-reference counting program languages, such as JAVA, cannot be automatically changed.
The amount of clearance work. It 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:

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 required by the framework of the program)
If a class is not ready to be inherited, it is best to specify it in the class document rather than define it as final.
This is because no one can guarantee whether or not to inherit from her for any reason.
Member variables of the category class
Most of the class member variables should be defined as protected to prevent the inherited class from using them.
Note that you must use "int [] packets" instead of "int packets []". The last one will never be used.

Public void setPackets (int [] packets) {this. packets = packets ;}

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




Programming Skills


Byte array to characters
To convert byte arrays to characters, you can do this:

"Hello world! ". GetBytes ();


Utility Class
Utility classes (classes that only provide methods) should be declared abstract to prevent inheritance or initialization.


Initialization
The following code is a good method for initializing Arrays:

ObjectArguments = new Object [] {arguments };


Enumeration type
JAVA does not support enumeration well, 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 technology implements RED, GREEN, BLUE, and other constants that can be used as enumeration types in other languages.
They can be compared using the '=' operator.
However, this method has a defect: if a user uses this method to create a color BLACK

New Colour (0, 0)

This is another object. The '=' operator produces an error. Her equal () method is still valid.
For this reason, it is best to indicate the technical defects in the document or use them only in your own package.

Swing


Avoid using AWT components
Hybrid use of AWT and Swing Components
Be careful when mixing the AWT and Swing components. In fact, try not
They need to be used together.


Rolling AWT component
The AWT component must not use the JscrollPane class for scrolling. Make sure to use it when rolling the AWT component
AWT ScrollPane component.


Avoid using the AWT component in the InternalFrame component
Do not do this as much as possible. Otherwise, unexpected consequences may occur.


Z-Order
The AWT component is always displayed on the Swing component. To use the POP-UP menu containing the AWT component
Be careful. Try not to use it like this.



Debugging


Debugging is an important part in software development. It is included in each part of the software life cycle. Debugging capability
Configuration on and off is the most basic.

One of the most common debugging methods is to use a member of The PrintStream class.
Null. The class must define a debug method to set the stream for debugging.



Performance


When writing code, you should consider performance issues from the beginning to the end. This does not mean that time should be wasted on optimization code,
Instead, we should always remind ourselves to pay attention to the code efficiency. For example, if there is no time to achieve an efficient
Algorithm, so we should record it in the document so that we can implement it later when we are free.

Not all people agree that the performance should be optimized when writing code. They think Performance Optimization Problems
It should be considered later in the project, that is, after the outline of the program has been implemented.
Unnecessary Object Construction
Do not create or release objects in a loop


Use StringBuffer object
Use the StringBuffer class whenever possible during String processing. The StringBuffer class is a String class.
. The String class encapsulates the StringBuffer class (at the cost of more time) for development.
Personnel provide a secure interface. When constructing a string, we should use StringBuffer
To achieve most of the work. After the work is completed, the StringBuffer object is converted to the required String object.
For example, if a string must be constructed by adding many characters after it, we should
Use the StringBuffer object and her append () method. If we use a String object instead of StringBuffer
Object, it will take a lot of unnecessary time to create and release the CPU of the object.

Avoid using too many synchronized keywords.
Avoid unnecessary use of the keyword synchronized and use it again when necessary.
A good way to lock.

Portability
Borland Jbulider does not like the synchronized keyword. If your breakpoint is set
In the scope, when debugging, you will find that the breakpoint will jump everywhere, making you overwhelmed. Unless required, do
Do not use.


Line feed
If you need to wrap a line, use println instead of "\ n" in the string ".
Do not:

System. out. print ("Hello, world! \ N ");

To do this:

System. out. println ("Hello, world! ");

Or you can construct a string with line breaks, at least like this:

String newline = System. getProperty ("line. separator ");
System. out. println ("Hello world" + newline );


PrintStream
PrintStream has been used by deprecated instead of PrintWrite.

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.