Java Coding Specification

Source: Internet
Author: User
Tags class definition naming convention

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

n Use full English descriptors as much as possible
n Use terminology appropriate to the relevant field
n a mixed case to make the name readable
n Minimize abbreviations, but if used, use wisely and unify throughout the project
n Avoid using long names (less than 15 letters is a good idea)
N Avoid using a similar name, or just a different name for the case
N Avoid using underscores (except static constants, etc.)

1.2 Demonstration

The package uses a full English descriptor, which should all be made up of lowercase letters. For the global package, reverse your Internet domain name and add the package name. Java.awt,com.ambysoft.www.persistence
Class takes the full English descriptor, with the first letter of all words capitalized. Customer, SavingsAccount
The interface (Interface) uses a full English descriptor to describe the interface encapsulation, with the first letter capitalized for all words. Traditionally, the name is appended with the suffix able, ible or er, but this is not required. Contactable,prompter
Components/Parts (Component) Use the full English description to describe the purpose of the component, and the component type on the end bell. OKButton, Customerlist,filemenu
An exception (Exception) usually uses the letter E to indicate an exception. E
Class variable fields are described in full English, with the first letter lowercase and the first letter of any intermediate word capitalized. FirstName, LastName
Argument/parameter same field/attribute naming convention public void Setfirstname (String firstName) {this.firstname = FirstName;}
Naming rules for local variables with fields/attributes
Gets the member function that is accessed by prefixing the field name with Get. Getfirstname (), Getlastname ()
The 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 that is accessed by the field name. Setfirstname (), Setlastname (), Setwarpspeed ()
The general member function uses the full English description to describe the member function function, the first word as far as possible to use a vivid verb, the first letter lowercase. OpenFile (), AddAccount ()
static 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 counter. I, J, K, counter
Array arrays should always be named in the following way: objecttype[]. 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

N comments should increase the clarity of the code
n Keep the annotations concise
N Write a comment before writing the code
N comment out why something has been done, not just what has been done
2.2. Demonstration
Document annotations annotate them immediately before interfaces, classes, member functions, and field declarations. /** Customer: The customer is the person or organization to whom we sell our services and products. */
The C language style uses a C-style comment to remove code that you no longer use but 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. /* This part of the code has been replaced by its previous code, commented out on June 4, 1999 by B.gustafsson. If it is not used after two years, delete it. . . . (source code) */
A single line takes a single-line comment within a member function to illustrate the declaration of business logic, code snippets, and temporal variables. The comment symbol "//" must be followed by a space, then the comment information. According to Sarek, give all//over $1000 invoices//5% discount. Let live//move started in February 1995.
2.3. Note which sections
The purpose of the class class, which is what the class does, comments out the invariant 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
http://hovertree.com/menu/java/
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:
/** * Shanghai XXX Co. Ltd. hovertree.com * All right reserved. */
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-be watched, but only * repo RTS 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); Error
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.

Recommendation: http://www.cnblogs.com/roucheng/p/3504465.html

Java Coding Specification

Related Article

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.