Java code specification

Source: Internet
Author: User

 

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.

I. 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:

 
  1. byte[] buffer;

Instead:

 
  1. byte buffer[];

> Method parameters

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

 
  1. SetCounter(int size){
  2. this.size = size;
  3. }

Ii. 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:

 
  1. /**
  2. * Copyright ?2000 Shanghai XXX Co. Ltd.
  3. * All right reserved.
  4. */

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.

 
  1. package hotlava.net.stats;
  2. import java.io.*;
  3. import java.util.Observable;
  4. 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.

 
  1. /**
  2. * A class representing a set of packet and byte counters
  3. * It is observable to allow it to be watched, but only
  4. * reports changes when the current set is complete
  5. */

The following is the class definition, including the extends and implements of different rows:

 
  1. public class CounterSet
  2. extends Observable
  3. implements Cloneable

> Class Fields

The following is the member variable of the class:

 
  1. /**
  2. * Packet counters
  3. */
  4. 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.

 
  1. /**
  2. * Get the counters
  3. * @return an array containing the statistical data. This array has been
  4. * freshly allocated and can be modified by the caller.
  5. */
  6. public int[] getPackets() { return copyArray(packets, offset); }
  7. public int[] getBytes() { return copyArray(bytes, offset); }
  8. public int[] getPackets() { return packets; }
  9. 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 ).

The 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, this makes the methods and parameters easier to read.

 
  1. public
  2. CounterSet(int size){
  3. this.size = size;
  4. }

> Clone method

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

 
  1. public
  2. Object clone()
  3. {
  4. try {
  5. CounterSet obj = (CounterSet)super.clone();
  6. obj.packets = (int[])packets.clone();
  7. obj.size = size;
  8. return obj;
  9. }catch(CloneNotSupportedException e) {
  10. throw new InternalError("Unexpected CloneNotSUpportedException: " + e.getMessage());
  11. }
  12. }

> Class Method

The following describes how to write a class:

 
  1. /**
  2. * Set the packet counters
  3. * (such as when restoring from a database)
  4. */
  5. protected final void setArray(int[] r1, int[] r2, int[] r3, int[] r4)throws IllegalArgumentException
  6. {
  7. //
  8. // Ensure the arrays are of equal size
  9. //
  10. if (r1.length != r2.length || r1.length != r3.length || r1.length != r4.length)
  11. throw new IllegalArgumentException("Arrays must be of the same size");
  12. System.arraycopy(r1, 0, r3, 0, r1.length);
  13. System.arraycopy(r2, 0, r4, 0, r1.length);
  14. }

> Tostring Method

In any case, each class should define the tostring method:

 
  1. public String toString()
  2. {
  3. String retval = "CounterSet: ";
  4. for (int i = 0; i<data.length();i++){
  5. retval += data.bytes.toString();
  6. retval += data.packets.toString();
  7. }
  8. return retval;
  9. }

> Main method

If the main (string []) method has been defined, it should be written at the bottom of the class.

Iii. code writing format

> Code style

The Code should be in UNIX format, rather than 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 different source code management tools are used, the Tab character is extended to different widths due to different user 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 correct because the 2nd rows are incorrect:

 
  1. If (I> 0) {I ++}; // error, {And} are in the same row
  2. If (I> 0 ){
  3. I ++
  4. }; // 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 examples describe errors and correct use of parentheses and spaces:

 
  1. Callproc (aparameter); // Error
  2. 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:

 
  1. If (I) = 42) {// error-Parentheses meaningless
  2. If (I = 42) or (j = 42) Then // correct-brackets are required.

Iv. Programming specifications

> 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:

 
  1. ...
  2. {
  3. FileOutputStream fos = new FileOutputStream(projectFile);
  4. project.save(fos, "IDE Project File");
  5. }
  6. ...

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:

 
  1. FileOutputStream fos = new FileOutputStream(projectFile);
  2. project.save(fos, "IDE Project File");
  3. fos.close();

> Clone

The following is a useful method:

 
  1. implements Cloneable
  2. public
  3. Object clone()

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.