Java coding specification, java Coding

Source: Internet
Author: User
Tags what parameter

Java coding specification, java Coding

1. Java Naming Conventions

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

1.1 General Concepts

N use the complete English descriptor whenever possible
N use terminology applicable to relevant fields
N uses a mix of upper and lower case to make the name readable
N should be used as few abbreviations as possible, but it should be used wisely and unified throughout the project.
N avoid using long names (it is a good idea to have less than 15 letters)
N avoid using similar names, or only names with different cases.
N avoid using underscores (except static constants)

1.2 demonstration

A Package uses a complete English descriptor, which must be composed of lowercase letters. For global packages, reverse your Internet domain name and connect the package name. Java. awt, com. ambysoft. www. persistence
Class uses a complete English descriptor, and the first letter of all words is capitalized. Customer, SavingsAccount
Interfaces are encapsulated using the complete English descriptor description Interface. The first letter of all words is capitalized. Traditionally, the name is followed by the suffix "able", "visible", or "er", but this is not necessary. Contactable, Prompter
Components/components (Component) Use a complete English description to describe the purpose of the Component. The end should be connected to the Component type. OkButton, customerList, fileMenu
Exception usually uses the letter e to indicate an Exception. E
The class variable field uses a complete English description. The first letter is lowercase, and the first letter of any intermediate word is uppercase. FirstName, lastName
Public void setFirstName (String firstName) {this. firstName = firstName ;}
Naming rules for local variables with the same field/attribute
Get the prefix "get" before the field name accessed by the member function. GetFirstName (), getLastName ()
Boolean get all the Boolean get functions of a member function must use the word "is" as the prefix. IsPersistent (), isString ()
Set the prefix set before the field name accessed by the member function. SetFirstName (), setLastName (), setWarpSpeed ()
Ordinary member functions use a complete English description to describe member functions. The first word uses a vivid verb as much as possible, and the first letter is in lowercase. OpenFile (), addAccount ()
Static final fields are all uppercase letters separated by underscores. MIN_BALANCE, DEFAULT_DATE
Cyclic counters are generally accepted by letters I, j, k, or counter. I, j, k, counter
The array should always be named in the following way: objectType []. Byte [] buffer;
2. Java annotations

A good rule of thumb that can be followed is: ask yourself, if you have never seen this code before, you must understand it effectively within a reasonable period of time, what information do you need.

2.1. General Concepts

N comments should increase the Definition of the code
N Keep comments concise
N write comments before writing code
N. Comment out why something has been done, not just what it has.
2.2. Demonstration
Document comments comment on interfaces, classes, member functions, and field declarations. /** Customer: the customer is the person or organization we sell services and products. */
C-style annotations remove the code that is no longer used but you still want to retain. I still want to keep it because the user wants to change his mind or temporarily disable it during debugging. /* This part of the code has been replaced by the previous code, which was commented out by B. Gustafsson on April 9, June 4, 1999. If it is not used two years later, delete it .. .. (Source code )*/
A single row uses a single line comment in a member function to describe the declaration of business logic, code segments, and temporary variables. The annotator "//" must be followed by a space and followed by a comment. // According to Sarek, a 1000 discount will be given to all waybills that exceed $ 5%. Let the promotion start on March 13, February 1995.
2.3. Comments
The purpose of the class, that is, the function completed by the class, and the immutability.
Set the purpose of the interface, how it should be used, and how it should not be used.
Member function comments can be used to set and obtain member functions without comments if the member variables already have descriptions. Common member functions must describe what functions are completed and what parameter meanings are returned;
The internal comment control structure of common member functions, what the code has done, why it is done, and the processing sequence.
Meanings of parameters and any other constraints or prerequisites
Field/attribute field description
Without comments when local variables are meaningless
3. Java file style conventions
Http://hovertree.com/menu/java/
All Java (*. java) files must comply with the following style rules:
1) Copyright Information
The copyright information must start with a java file, for example:
/*** Copyright 2016 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
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.
3) 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 {......}
4) 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.
5) access method (class setting and getting member functions)
Next is the method for accessing class variables. It is simply used to assign values to class variables, and you can simply write them in a row. For example, the class member variables already have comments, and the class variable access method can have no comments.
Public int [] getPackets () {return this. packets;} public void setPackets (int [] packets) {this. packets = packets ;}......
It must be noted that for a set, add member functions to insert and delete items. Other methods should not be written on one line.
6) 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 ).
Public CounterSet (int size) {this. size = size ;}
7) clone method
If this class can be cloned, the next step is the clone method:
Public Object clone () {try {...... } Catch (CloneNotSupportedException e ){...... }}
8) class methods (common member functions of the Class)
The following describes how to write a class:
/*** 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 are of equal size ......}
9) toString Method
Generally, each class should define the toString method:
Public String toString (){......}
10) main method
For a common class, consider placing a main () method, which contains the code used to test that class. If the main () method is included, it should be written at the bottom of the class.

4. other Java coding conventions

N docalization
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.
N indent
Indentation should contain 2 spaces in each line. Do not save the Tab character in the source file. When different source code management tools are used, 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.
N 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.
N {} pair
The statement in {} should be a separate row. For example, the following row 1st is incorrect, and the row 2nd is correct:
If (I> 0) {I ++}; // error, {And} are in the same row if (I> 0) {I ++}; // correct, separate as a row
N 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 examples describe 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.
N JSP file name
A complete English description is used to describe the functions completed by JSP, including a vivid verb, the first letter in lowercase, such as viewMessage. jsp, editUser. jsp, or forumChooser. jsp.
N Servlet Class Name
Generally, the Service name corresponds to the Service object and the suffix Service, such as UserService and TradeService.

5. Some programming suggestions

N use the StringBuffer object
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 its 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.
N avoid using too many synchronized keywords
Avoid unnecessary use of the keyword synchronized and use it when necessary. This is a good way to avoid deadlocks. The range should be controlled whenever necessary. It is best to control the range at the block level.
N avoid using java. util. Vector class
Because "Unlike the new collection implementations, Vector is synchronized.", the use of java. util. Vector classes reduces the performance.
N try to use interfaces instead of a specific class
For example, if you want to give an SQL statement and return a list of objects, you can use java. util. ArrayList to implement it. The definition method is as follows:
Public java. util. ArrayList getObjectItems (String SQL)
There is a problem with the above method. When the implementation of getObjectItems is implemented using Vector or shortlist, the external class must be changed accordingly. A better way is to define the return value as java. util. AbstractList. It is more appropriate:
Public java. util. AbstractList getObjectItems (String SQL)
In this way, the external class does not need to be changed even if it is implemented.
N avoid using indexes to call the result set returned by the database intermediate layer component
For example:
For (int I = 1; I <= dt. getRowCount (); I ++) {String field1 = dt. getField (I, 0). toString ();......}
The application field name is used to access the result set:
For (int I = 1; I <= dt. getRowCount (); I ++) {String field1 = dt. getField (I, "field1 "). toString ();......}
In this way, the execution of the program will not be affected when the database design changes or the queried SQL statement changes.

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

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.