Java program coding specification

xiaoxiao2021-03-06  52

All procedures development brochures contain various rules. Some customary free proceeders may not be adapted to these rules, but these rules are required in the case of working with multiple developers. This is not only for development efficiency, but also for later maintenance considerations.

Naming conventions

All procedures development brochures contain various rules. Some customary free proceeders may not be adapted to these rules, but these rules are required in the case of working with multiple developers. This is not only for development efficiency, but also for later maintenance considerations.

Naming Specifications Definition The purpose of this specification is to make all documents in the project look like a person written, increase readability, and reduce the loss in the project group because of the loss. (These norms are not necessarily abolished, but must have a good readability)

The name of the name of Package should be composed of a lowercase word.

The name of the Class's named Class must be made by uppercase letters and other letters.

The name of the name variable of the Class variable must be started with a lowercase letter. The latter words begin with uppercase letters.

The name of the Static Final variable should be capitalized and point out the full meaning.

The name of the naming parameters of the parameters must be consistent with the naming specification of the variable.

The named array of arrays should always be named in the following way:

BYTE [] BUFFER

Instead:

BYTE BUFFER [];

The parameters of the method use meaningful parameters, if possible, use the same name as the field to assign value:

SetCounter (int size) {this.size = size;}

The Java file style has a Java (*. Java) file must comply with the following style rules.

Copyright Information The copyright information must be on the beginning of the Java file, such as:

/ ** * Copyright? 2000 Shanghai xxx Co. Ltd. * all rights reserved. * /

Others do not need to appear in Javadoc, can also be included here.

Package / ImportsPackage Row Before the IMPORT row, the standard package name in the Import is previously in the local package name, and arranged in alphabetical order. If the IMPORT line contains different subdirectory in the same package, you should use * to process.

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.

Class is next to the annotation of the class, usually used to interpret the class.

/ ** * a class representing a set of packet and byte counters * it is observable to allow it to be watch, but only * reports change,

Next is a class definition, including extends and imports in different rows.

Public Class Counterset Extends Observable Implements Cloneable

Class Fields Next is a member variable of class:

/ ** * packet counter * / protected int [] packets;

Public member variables must generate a document (javadoc). Member variables defined by Proceted, Private and Package If the name meaning is clear, you can not comment.

Access method Next is a method of access to class variables. It is just simple to get values ​​to assign values ​​to the class variable, you can simply write on one line.

/ ** * 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;}

Other methods don't write on a line

The constructor is next to the constructor, which should be written in an incremental manner (such as: writing more than the parameter). Access Type ("Public", "Private", etc.) and any "static", "firm" or "synchronized" should be written in one line, and the methods and parameters can be written separately, which makes the method and parameters easier to read.

PubliccounterSet (int size) {this.size = size;}

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

Publicobject Clone () {Try {counter = (counter) super.clone (); obj.packets = (int []) packets.clone (); obj.size = size; return} catch (clonenotsuportedException E) { Throw new interfacerror ("UNEXPECTED ClonyNotSupportedException:" E.getMessage ());}}

Class Method Next: Method for writing classes:

/ ** * set the packet counters * (Such as When Restoring from a database) * / protected finalvoid setArray (int [] R1, int [] R2, int [] R3, int [] R4) throws illegalgumentException {// / / Ensure the arrays area of ​​equal size // if (r1.length! = R2.Length || r1.length! = R3.Length || r1.length! = R4.length) throw new illegalargumentException ("Arrays Must Be "); System.ArrayCopy (R1, 0, R3, 0, R1.LENGTH); System.ArrayCopy (R2, 0, R4, 0, R1.LENGTH);}

The TOSTRING method should define the toString method in any case:

PUBLICSTRING TOSTRING () {string retval = "counter"; for (int i = 0; i

Code writing format

Code style code should use UNIX's format, not Windows (such as: Enter the carriage return wrap)

Documentization must use javadoc to generate a document for class. Not only because it is standard, this is also a method recognized by various Java compilers. Using the @Author tag is not recommended because the code should not be owned by the individual.

The indental indentation should be 2 space per line. Do not save the Tab character in the source file. Tab characters will be extended to different widths because the user settings are used in different source code management tools. If you use Ultredit as If your Java source editor, you can prohibit saving Tab characters by using the following operations, using the length of the length of the tab used in the ULTREDIT, then use the Format | Tabs to Spaces menu to convert TAB to spaces .

Page width width should be set to 80 characters. Source code will not exceed this width and causing unable to display, but this setting can also be flexible. In any case, the long statement should be in a comma or one action After the folding. After a statement is folded, 2 characters should be indented more than the original statement.

{} The statement in {} should be a row alone. For example, the first line below is wrong, the second line is correct:

IF (i> 0) {i }; // error, {and} in the same line

IF (i> 0) {i }; // correct, {alone

} The statement is always separate as a line.

If the} statement should be indented to the {that row relatively aligned with it.

There should be a space between the parentheses left parentheses and the latter characters. Similarly, there should be no space between the right brackets and the previous characters. The following example shows the incorrect of parentheses and spaces and correct usage: CallProc (APARAMETER); // Error CallProc (APARAMETER); // Do not use meaningless parentheses in the statement. Braces should only be in the source code to achieve some purpose. The following example illustrates errors and correct usage: if ((i) = 42) {// error - parentheses meaningless if (i == 42) or (j == 42) THEN // correct - indeed parentheses

Program writing specification

EXIT () EXIT In addition to being called in main, other places should not be called. Because this does not give any code code opportunities to intercept exit. A similar background service ground program should not be exited because a library module determines to exit.

An abnormally declared error should throw a runtimeException or derived exception. The top () function of the top layer should intercept all exceptions and print (or record it in the log) on ​​the screen.

Garbage collection Java uses mature background garbage collection techniques instead of reference count. But this will result in a problem: You must work after the instance of the object is used. For example, a PREL programmer may write:

... {fileoutputstream fos = new fileoutputstream (projectfile); Project.save (FOS, "IDE Project File");} ...

Unless the output stream is turned off, it is not a reference to the program language, such as Java, is a clearing work of the variable. Must be written as follows: FileOutputStream Fos = New FileoutputStream (ProjectFile); Project.Save (FOS, "Ide Project File"; fos.close ();

The following is a useful method:

Implements Cloneable

Public Object Clone () {THISCLASS) Super.clone (); obj.field1 = (int []) Field1.clone (); obj.field2 = field2; returnobj;} catch (ClonenOtSupportedException E) {Throw new interNalerror ("Unexpected ClonyNotSupportedException:" E.getMessage ());}}

The Final class is absolutely not to define the class as final (unless the program frame requirements) if a class is not ready to be inherited, not to define her as Final. This is because no one can guarantee that it will not be inherited because of what reason.

Most of the members variables of the members of the access class should be defined as protected to prevent inheritance classes. Note, use "int [] packets" instead of "int packets []", the latter is never used.

Public void setpackets (int [] packets) {this.packets = packets;}

INTERSET (INT size) {this.size = size;}

Program skill

Byte array transition to Characters In order to convert the BYTE array to Characters, you can do this: "Hello World!". Gettes ();

The Utility class UTILITY class (class only provides a class) should be stated to abstract to prevent inheritance or initialization.

Initializing the following code is a good method of initialization array: Objectarguments = new object [] {arguments}

Enumeration Type Java is not good for enumeration, but the following code is a useful template:

Class colour {public static final colour black = new color static final color red = new color final color set = new color final color green = new color final color green = new color (0, 0xff, 0) Public Static Final Color Blue = New Colour (0, 0, 0xFF); Public Static Final Colour White = New Colour (0xFF, 0xFF, 0xFF);

This technology implements constants that can be used like the types of enumerations such as other languages. They can compare with '==' operators. But this is used in this way: if a user uses such a method to create a color Blacknew color (0,0,0) then this is another object, '==' operator generates an error. Her equal () method is still valid. For this reason, the defect of this technology is best to indicate in the document, or only in your own package. Swing

Avoid using AWT components

Mixing Use the AWT and SWING components If you want to mix the AWT components and Swing components, use it. In fact, try not to mix them up.

Scrolling AWT component AWT components must not use JScrollPane classes to implement scrolling. When scrolling the AWT component, you must use the AWT SCROLLPANE component to be implemented.

Avoid using AWT components to do so as much as possible in the InternalFrame component, or there will be unpredictable consequences.

Z-Order issues The AWT component is always displayed on the Swing component. Be careful when using the POP-UP menu containing the AWT component, try not to use it like this.

debugging

Debugging is a very important part of software development, exists in various parts of the software lifecycle. Debug can be opened with configuration, the key is the most basic. A very commonly used debugging method is to use a PrintStream class member, when not defined the trial flow, the class wants to define a DEBUG method to set the stream of debugging.

performance

When writing code, you should consider performance issues from head until tails. This is not to say that time should be wasted on the optimization code, but we always remind yourself to pay attention to the efficiency of the code. For example, if there is no time to implement an efficient algorithm, then we should record in the document so that you will come again in the future. Not all people agree to optimize the performance of this view when writing code, and they think that performance optimization should be considered in the later stage of the project, that is, after the outline of the program has been implemented.

Unnecessary object structure

Do not construct and release objects in the loop

Using the StringBuffer object When processing String, try to use the StringBuffer class as possible, and the StringBuffer class is the basis for constituting the String class. The String class encapsulates the StringBuffer class, (at the expense of more time) provides a secure interface to developers. When we are constructing a string, we should use StringBuffer to implement most of the work, and convert the StringBuffer object to the required String object when the work is completed. For example, if there is a string that must be constantly adding a lot of characters to complete the construct, we should use the StringBuffer object and her append () method. If we use the String object instead of the StringBuffer object, you will spend a lot of unnecessary CPU time to create and release the object.

Avoid too much use synchronized keyword to avoid unnecessary use of keyword synchronized, should use her when necessary, this is a good way to avoid deadlocks.

Portability Borland Jbulider does not like synchronized this keyword. If your breakpoint is located in the scope of these keywords, you will find the breakpoint when you debug, let you do it. Minimize not to use unless you must

If you need to wrap, try to use PrintLn to use "/ n" in a string. You don't want this: system.out.print ("Hello, World! / N"); you should: system.out.println ("Hello, World!"); Or you construct a string with changing lines, at least Like this: string newline = system.getProperty ("line.separator"); system.out.println ("Hello World"; PrintStreamPrintStream has been used without admission, replacing her with printwrite.

These specifications are not necessarily abolished, but must make the program have good readability)

The name of the name of Package should be composed of a lowercase word.

The name of the Class's named Class must be made by uppercase letters and other letters.

The name of the name variable of the Class variable must be started with a lowercase letter. The latter words begin with uppercase letters.

The name of the Static Final variable should be capitalized and point out the full meaning.

The name of the naming parameters of the parameters must be consistent with the naming specification of the variable.

The named array of arrays should always be named in the following way:

BYTE [] BUFFER

Instead:

BYTE BUFFER [];

The parameters of the method use meaningful parameters, if possible, use the same name as the field to assign value:

SetCounter (int size) {this.size = size;}

The Java file style has a Java (*. Java) file must comply with the following style rules.

Copyright Information The copyright information must be on the beginning of the Java file, such as:

/ ** * Copyright? 2000 Shanghai xxx Co. Ltd. * all rights reserved. * /

Others do not need to appear in Javadoc, can also be included here.

Package / ImportsPackage Row Before the IMPORT row, the standard package name in the Import is previously in the local package name, and arranged in alphabetical order. If the IMPORT line contains different subdirectory in the same package, you should use * to process.

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.

Class is next to the annotation of the class, usually used to interpret the class.

/ ** * a class representing a set of packet and byte counters * it is observable to allow it to be watch, but only * reports change,

Next is a class definition, including extends and imports in different rows.

Public Class Counterset Extends Observable Implements Cloneable

Class Fields Next is a member variable of class:

/ ** * packet counter * / protected int [] packets;

Public member variables must generate a document (javadoc). Member variables defined by Proceted, Private and Package If the name meaning is clear, you can not comment. Access method Next is a method of access to class variables. It is just simple to get values ​​to assign values ​​to the class variable, you can simply write on one line.

/ ** * 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;}

Other methods don't write on a line

The constructor is next to the constructor, which should be written in an incremental manner (such as: writing more than the parameter). Access Type ("Public", "Private", etc.) and any "static", "firm" or "synchronized" should be written in one line, and the methods and parameters can be written separately, which makes the method and parameters easier to read.

PubliccounterSet (int size) {this.size = size;}

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

Publicobject Clone () {Try {counter = (counter) super.clone (); obj.packets = (int []) packets.clone (); obj.size = size; return} catch (clonenotsuportedException E) { Throw new interfacerror ("UNEXPECTED ClonyNotSupportedException:" E.getMessage ());}}

Class Method Next: Method for writing classes:

/ ** * set the packet counters * (Such as When Restoring from a database) * / protected finalvoid setArray (int [] R1, int [] R2, int [] R3, int [] R4) throws illegalgumentException {// / / Ensure the arrays area of ​​equal size // if (r1.length! = R2.Length || r1.length! = R3.Length || r1.length! = R4.length) throw new illegalargumentException ("Arrays Must Be "); System.ArrayCopy (R1, 0, R3, 0, R1.LENGTH); System.ArrayCopy (R2, 0, R4, 0, R1.LENGTH);}

The TOString method should define the TOString method in each class: publicString toString () {string retval = "counterset:"; for (int i = 0; i

Main method If the main (String []) method is already defined, it should be written at the bottom of the class.

Code writing format

Code style code should use UNIX's format, not Windows (such as: Enter the carriage return wrap)

Documentization must use javadoc to generate a document for class. Not only because it is standard, this is also a method recognized by various Java compilers. Using the @Author tag is not recommended because the code should not be owned by the individual.

The indental indentation should be 2 space per line. Do not save the Tab character in the source file. Tab characters will be extended to different widths because the user settings are used in different source code management tools. If you use Ultredit as If your Java source editor, you can prohibit saving Tab characters by using the following operations, using the length of the length of the tab used in the ULTREDIT, then use the Format | Tabs to Spaces menu to convert TAB to spaces .

Page width width should be set to 80 characters. Source code will not exceed this width and causing unable to display, but this setting can also be flexible. In any case, the long statement should be in a comma or one action After the folding. After a statement is folded, 2 characters should be indented more than the original statement.

{} The statement in {} should be a row alone. For example, the first line below is wrong, the second line is correct:

IF (i> 0) {i }; // error, {and} in the same line

IF (i> 0) {i }; // correct, {alone

} The statement is always separate as a line.

If the} statement should be indented to the {that row relatively aligned with it.

There should be a space between the parentheses left parentheses and the latter characters. Similarly, there should be no space between the right brackets and the previous characters. The following example shows the incorrect of parentheses and spaces and correct usage: CallProc (APARAMETER); // Error CallProc (APARAMETER); // Do not use meaningless parentheses in the statement. Braces should only be in the source code to achieve some purpose. The following example illustrates errors and correct usage: if ((i) = 42) {// error - parentheses meaningless if (i == 42) or (j == 42) THEN // correct - indeed parentheses

Program writing specification

EXIT () EXIT In addition to being called in main, other places should not be called. Because this does not give any code code opportunities to intercept exit. A similar background service ground program should not be exited because a library module determines to exit.

An abnormally declared error should throw a runtimeException or derived exception. The top () function of the top layer should intercept all exceptions and print (or record it in the log) on ​​the screen.

Garbage collection Java uses mature background garbage collection techniques instead of reference count. But this will result in a problem: You must work after the instance of the object is used. For example, a PREL programmer may write:

... {FileOutputStream Fos = New FileOutputStream (Projectfile); Project.Save (FOS, "Ide Project File");} ... Unless the output stream is turned off, it is close to the program language, such as Java, Is it possible to automatically complete the variable. Must be written as follows:

FileOutputStream Fos = New FileoutputStream (Projectfile); Project.Save (FOS, "Ide Project File"; fos.close ();

The following is a useful method:

Implements Cloneable

Public Object Clone () {THISCLASS) Super.clone (); obj.field1 = (int []) Field1.clone (); obj.field2 = field2; returnobj;} catch (ClonenOtSupportedException E) {Throw new interNalerror ("Unexpected ClonyNotSupportedException:" E.getMessage ());}}

The Final class is absolutely not to define the class as final (unless the program frame requirements) if a class is not ready to be inherited, not to define her as Final. This is because no one can guarantee that it will not be inherited because of what reason.

Most of the members variables of the members of the access class should be defined as protected to prevent inheritance classes. Note, use "int [] packets" instead of "int packets []", the latter is never used.

Public void setpackets (int [] packets) {this.packets = packets;}

INTERSET (INT size) {this.size = size;}

Program skill

Byte array transition to Characters In order to convert the BYTE array to Characters, you can do this: "Hello World!". Gettes ();

The Utility class UTILITY class (class only provides a class) should be stated to abstract to prevent inheritance or initialization.

Initializing the following code is a good method of initialization array: Objectarguments = new object [] {arguments}

Enumeration Type Java is not good for enumeration, but the following code is a useful template:

Class colour {public static final colour black = new color static final color red = new color final color set = new color final color green = new color final color green = new color (0, 0xff, 0) Public static final colour blue = new color final color White = new color final color white = new color (0xFF, 0xFF, 0xFF);} This technology implements RED, Green, Blue, etc. can like other languages. Enumerate types of constants are used. They can compare with '==' operators. But this is used in this way: if a user uses such a method to create a color Blacknew color (0,0,0) then this is another object, '==' operator generates an error. Her equal () method is still valid. For this reason, the defect of this technology is best to indicate in the document, or only in your own package.

Swing

Avoid using AWT components

Mixing Use the AWT and SWING components If you want to mix the AWT components and Swing components, use it. In fact, try not to mix them up.

Scrolling AWT component AWT components must not use JScrollPane classes to implement scrolling. When scrolling the AWT component, you must use the AWT SCROLLPANE component to be implemented.

Avoid using AWT components to do so as much as possible in the InternalFrame component, or there will be unpredictable consequences.

Z-Order issues The AWT component is always displayed on the Swing component. Be careful when using the POP-UP menu containing the AWT component, try not to use it like this.

debugging

Debugging is a very important part of software development, exists in various parts of the software lifecycle. Debug can be opened with configuration, the key is the most basic. A very commonly used debugging method is to use a PrintStream class member, when not defined the trial flow, the class wants to define a DEBUG method to set the stream of debugging.

performance

When writing code, you should consider performance issues from head until tails. This is not to say that time should be wasted on the optimization code, but we always remind yourself to pay attention to the efficiency of the code. For example, if there is no time to implement an efficient algorithm, then we should record in the document so that you will come again in the future. Not all people agree to optimize the performance of this view when writing code, and they think that performance optimization should be considered in the later stage of the project, that is, after the outline of the program has been implemented.

Unnecessary object structure

Do not construct and release objects in the loop

Using the StringBuffer object When processing String, try to use the StringBuffer class as possible, and the StringBuffer class is the basis for constituting the String class. The String class encapsulates the StringBuffer class, (at the expense of more time) provides a secure interface to developers. When we are constructing a string, we should use StringBuffer to implement most of the work, and convert the StringBuffer object to the required String object when the work is completed. For example, if there is a string that must be constantly adding a lot of characters to complete the construct, we should use the StringBuffer object and her append () method. If we use the String object instead of the StringBuffer object, you will spend a lot of unnecessary CPU time to create and release the object. Avoid too much use synchronized keyword to avoid unnecessary use of keyword synchronized, should use her when necessary, this is a good way to avoid deadlocks.

Portability Borland Jbulider does not like synchronized this keyword. If your breakpoint is located in the scope of these keywords, you will find the breakpoint when you debug, let you do it. Minimize not to use unless you must

If you need to wrap, try to use PrintLn to use "/ n" in a string. You don't want this: system.out.print ("Hello, World! / N"); you should: system.out.println ("Hello, World!"); Or you construct a string with changing lines, at least Like this: string newline = system.getProperty ("line.separator"); System.out.Println ("Hello World" Newline);

PrintStreamPrintStream has been used in favor (deprecated), with PrintWrite instead of her.

转载请注明原文地址:https://www.9cbs.com/read-115737.html

New Post(0)