Java Coding Specification

Source: Internet
Author: User

1. Java Naming conventions

In addition to the following exceptions, a full English descriptor should always be used for naming. In addition, lowercase letters should generally be used, but the class name, interface name, and the first letter of any non-initial word should be capitalized.

1.1 General Concepts

* Try to use full English descriptors

* Use of terminology applicable to related fields

* Use case mix to make name readable

* Minimize the use of abbreviations, but if used, use wisely and unify throughout the project

* Avoid using long names (less than 15 letters is a good idea)

* Avoid using a similar name, or just a different name for the case

* Avoid using underscores (except static constants, etc.)

1.2 Demonstration

* Packages with full English descriptors should be made up of lowercase letters. For the global package, reverse your Internet domain name and add the package name. Such as:
java.awt
Com.ambysoft.www.persistence

* Class is a full English descriptor with the first letter of all words capitalized. Such as:
Customer
SavingsAccount

* Interface (INTERFACE) uses a full English descriptor to describe the interface encapsulation, the first letter of all words capitalized. Traditionally, the name is appended with the suffix able, ible or er, but this is not required. Such as:
Contactable
Prompter

* Components/components (Component) Use the full English description to describe the purpose of the component, end Bell on the component type. Such as:
OKButton
CustomerList
Filemenu

* Exceptions (Exception) usually use the letter E to indicate an exception. E

* class variable fields are described in full English, with the first letter lowercase and any intermediate words capitalized in the first word, such as: FirstName
LastName

* Naming rules for argument/parameter same field/attribute
public void Setfirstname (String firstName) {
This.firstname = FirstName;
}

* Naming rules for local variables with fields/attributes

* * Gets the member function preceded by the Access field name prefixed by get. Getfirstname (), Getlastname ()

* * Boolean get member function all Boolean get functions must be prefixed with the word is. Ispersistent (), isstring ()

* * The set member function is preceded by a prefix set for the Access field name. Setfirstname (), Setlastname (), Setwarpspeed ()

* * The general member function uses the full English description to describe the function of the member function, the first word as far as possible to use a vivid verb, the first letter lowercase. OpenFile (), AddAccount ()

* Static and Constant fields (static final) are all uppercase letters, and the words are separated by underscores. Min_balance, Default_date

* The loop counter is usually accepted using either the letter I,j,k or the counter. I, J, K, counter

* Array arrays should always be named in the following way: byte[] buffer;
2. Java Annotation Conventions

A good rule of thumb to follow is: ask yourself, if you've never seen this code, you need to be able to understand it effectively within a reasonable period of time.

2.1. General Concepts

* Comments should increase the clarity of the code

* Keep the annotations simple

* Write comments before writing the code

* Comment out why something has been done, not just what has been done

2.2. Demonstration

* Documentation Comments
Comment them immediately before the interfaces, classes, member functions, and field declarations.
/**
*
* Customer: The customer is the person or organization that we sell the service and the product.
*/

* C language style
Use C-style annotations to remove code that is no longer used but that you still want to keep. Still want to keep it because the user will change the idea, or in the debugging process to let it temporarily expire. Such as:
/* This part of the code has been replaced by its previous code, by B.gustafsson, in June 1999
* 4th commented out. If it is not used after two years, delete it. . . .
* (source code)
*/

* Single Line
A single-line comment is used within the member function to describe the declaration of business logic, code snippets, and temporal variables. The comment symbol "//" must be followed by a space, then the comment information. Such as:
In accordance with Sarek's regulations, give all
More than $1000 invoices
A 5% discount. Let live
Started in February 1995.

2.3. Note which sections

The purpose of the class class, the function that the class completes, and comments out the variables used.

The interface sets the purpose of the interface, how it should be used, and how it is not used.

member function comments for the set and get member functions, in the case of member variables have been described, can not be annotated; Ordinary member functions require a description of what is done and what the parameter means to return;

General member functions internal annotation control structure, what the code does and why it is done, processing order, etc.

Argument/parameter meaning, and any other constraints or prerequisites

Field/attribute field description

Non-annotated when local variables are not particularly meaningful

3. Java File Style conventions

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

1) Copyright information

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

/**
* Copyright @ Shanghai XXX Co. Ltd.
* All right reserved.
* @author: GCGMH
* Date:2008-12-22
*/

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

2) 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.* is used instead of InputStream and OutputStream.

3) 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{
......
......
}

4) 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.

5) Access method (set of class and get member function)

Next is the method of accessing the class variable. It is simply used to get the value of the class variable assignment, can be simply written on one line, such as the class's member variable has been commented, the access method of the class variable can not be commented.

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

The requirement is that, for the collection, the member function is added to insert and delete the item, and the other method is not written on one line.

6) 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).

public counterset (int size) {this.size = size;}

7) Cloning method

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

Public Object Clone () {try {...} catch (Clonenotsupportedexception e) {...}}

8) class method (ordinary member function of Class)

Here's how to start writing classes:

/**
* Set the packet counters
* param R1-...
* param R2-...
* ......
*/
Protected final void SetArray (int[] R1, int[] R2, int[] R3, int[] R4) throws illegalargumentexception{
Ensure the arrays is of equal size
......
}

9) ToString method

In general, each class should define a ToString method:

Public String toString () {...}

) Main method

General class, consider placing a main () method that contains the code used to test the class, and if it contains the main () method, it should be written at the bottom of the class.

4. Java Coding Other Conventions

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

N Indent

The indentation should be 2 spaces per line. Do not save the tab character in the source file, and the tab character expands to a different width depending on the user settings when using different source control tools.

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.

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

n {} pairs

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 + +}; Right, as a single line

N 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); That's right

Instead of using meaningless parentheses in a statement, parentheses should only appear in the source code for some purpose.

N jsp file naming

Use the complete English description to illustrate the functions of the JSP, including as far as possible a vivid verb, the first letter lowercase, such as: viewmessage.jsp, edituser.jsp or forumchooser.jsp.

n servlet class naming

Generally corresponds to the service object plus suffix service to name, such as: Userservice,tradeservice.

5. Some programming recommendations

n 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 its 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.

N Avoid too much use of the Synchronized keyword

Avoid unnecessary use of keyword synchronized, it should be used when necessary, which is a good way to avoid deadlocks. Must be used when, also try to control the range, preferably in block-level control.

N Avoid using the Java.util.Vector class

Because "unlike the new collection implementations, Vector is synchronized.", the use of the Java.util.Vector class will decrease in performance.

n try to use an interface instead of a specific class

For example, the following requirement, given an SQL statement, returns a list of objects, implemented in Java.util.ArrayList, and the method is defined as:


Public java.util.ArrayList getobjectitems (String sql)

There is a problem with the method above, and the external class must make the corresponding changes when Getobjectitems is implemented in vector or LinkedList instead. A better way is to define a return value of java.util.AbstractList more appropriate:

Public java.util.AbstractList getobjectitems (String sql)

This makes it unnecessary for the external class to change even if the implementation is changed.

n Avoid using indexes to invoke result sets returned by the database middle tier component

Such as:

for (int i=1; I<=dt.getrowcount (); i++) {String field1 = Dt.getfield (i, 0). toString ();

Instead, apply the field name to access the result set:

for (int i=1; I<=dt.getrowcount (); i++) {String field1 = Dt.getfield (i, "field1"). ToString ();

This does not affect the execution of the program when the database design changes or the SQL statements of the query change.

Java Encoding Specification (RPM)

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.