Java code specification

Source: Internet
Author: User
Java code specification
All program development manuals contain various rules. Free programmers may be uncomfortable with these rules, but these rules are necessary when multiple developers write together. This is not only for development efficiency, but also for later maintenance.

Naming rules
The purpose of defining this specification is to make all the documents in the Project look as written by one person, increase readability, and reduce the loss caused by substitution in the project team. (These specifications are not always strictly observed, but must make the program readable)

* 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
The package line must be prior to the import line. The standard package names in the import must be prior to the local package name and are listed alphabetically. If the import line contains different subdirectories in the same package, use * for 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 ). Member variables defined by proceted, private, and package can be uncommented if the name has a clear meaning.

* Access Method
Next is the method for accessing class variables. It is simply used to obtain the value of the variable value of the class, you can simply write it on a row.

/**
* 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" 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 is it a standard, but it is also recognized by various Java compilers. Using the @ 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. When you use different source code management tools, the Tab character will be extended to different widths due to different settings.
If you use ultredit as your Java source code editor, you can do the following to disable the storage of TAB characters by setting the length of the tab using two spaces in ultredit, then, use the format | tabs to spaces menu to 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. However, this setting can be flexibly adjusted. 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 the brackets 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. 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. This does not give any code Code Opportunity to intercept and exit. A program similar to the background service should not exit because a database module decides to 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. However, this will cause a problem: You must clear the job after using the instance of the object. 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 automatically complete variable clearance. 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 that she will be inherited 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 conversion 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
O Hybrid use of AWT and swing Components
Be careful when mixing the AWT and swing components. In fact, try not to mix them together.

O rolling AWT components
The AWT component must not use the jscrollpane class for scrolling. The AWT scrollpane component must be used for Rolling AWT components.

O avoid using the AWT component in the internalframe component
Do not do this as much as possible. Otherwise, unexpected consequences may occur.

O z-order
The AWT component is always displayed on the swing component. When using the pop-up menu containing the AWT component, be careful 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 can be enabled or disabled with configuration.

One of the most common debugging methods is to use a member of The printstream class, which is null when the debugging stream is not defined. 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 code optimization, but we should always remind ourselves to pay attention to code efficiency. For example, if you don't have time to implement an efficient algorithm, you should record it in the document so that you can implement it when you are free.

Not all people agree that the performance should be optimized when writing code. They believe that the performance optimization problem should be considered later in the project, that is, after the outline of the program has been implemented.

* Unnecessary Object Construction
O do not create or release objects in a loop

O use stringbuffer objects
Use the stringbuffer class whenever possible during string processing. The stringbuffer class forms the basis of the string class. The string class encapsulates the stringbuffer class and provides a secure interface (at the cost of more time) for developers. When constructing strings, we should use stringbuffer to achieve most of the work. After the work is completed, the stringbuffer object will be 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 to replace the stringbuffer object, it will take a lot of unnecessary CPU time to create and release the object.

* Avoid using too many synchronized keywords.
Avoid unnecessary use of the keyword synchronized and use it again when necessary. This is a good way to avoid deadlocks.

Portability
Borland jbulider does not like the synchronized keyword. If your breakpoint is in the scope of these keywords, you will find that the breakpoint will jump everywhere during debugging, so that you are at a loss. Unless required, try not to use it.

* 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.