Coding | procedure | specification
Code specification for Java programs
Li Xiaomin
Www.yway.com Software Engineer
December 2000
content:Naming convention Java file Style code writing format program writing programming tips Swing Debugging Performance Portability Reference author introduction
all the program development manuals contain a variety of rules. Some custom-free program personnel may not be comfortable with these rules, but these rules are required when multiple developers write together. This is not only for the sake of development efficiency, but also for later maintenance considerations.
Naming Conventions
The purpose of defining this specification is to make all documents in the project appear to be written by one person, to increase readability, and to reduce the loss caused by substitutions in the project team. (These specifications are not necessarily strictly adhered to, but make sure that the program has good readability)
- The name of the Package
Package's name should all be made up of a lowercase word.
- Name of Class
Class must have a name that starts with a capital letter and other words are lowercase
- Name of Class variable
The name of the variable must begin with a lowercase letter. The following words begin with a capital letter.
- Name of Static Final variable
The Static Final variable's name should all be capitalized, and the full meaning is indicated.
- Name of the parameter
The name of the parameter must be the same as the variable's naming convention.
- Name of array
The array should always be named in the following way:
byte[] buffer;
Instead of:
BYTE buffer[];
Java file Style
All Java (*.java) files must conform to the following style rules
- Class
Next is the annotation for the class, which is generally used to interpret the class.
/** * A class representing a set of packet and byte counters * It is observable to allow the it to being watched, but only * repo RTS changes when the current set is complete * *
Next is the class definition, which contains the extends and implements in different rows
public class CounterSet extends observable implements Cloneable
- Access method
Next is the method of accessing the class variable. It is simply used to assign a value to a variable of a class, and it can be written on a single line.
/** * Get the counters * @return An array containing the statistical data. This array has been * freshly allocated and can is 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 ways not to write on one line
- class methods
to begin 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 illegalargumentexception{ //& nbsp; //ensure the arrays are of equal size // if (r1.length!= r2.length | | r1.length!= R3.L Ength | | R1.length!= r4.length) throw new IllegalArgumentException ("Arrays must be of the same size");
Nbsp; system.arraycopy (R1, 0, R3, 0, R1.length); system.arraycopy (R2, 0, R4, 0, r1.length);
- 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
The code should be in UNIX format, not Windows (for example: carriage return to carriage return + newline)
- Documented
You must use Javadoc to generate a document for your class. Not only is it a standard, it is also a method that is approved by various Java compilers. Using @author tags is not recommended, because the code should not be owned by the individual.
- Indent
Indents should be 2 spaces per line. Do not save the tab character in the source file. When you use a different source control tool, the tab character expands to a different width because of user settings.
If you use Ultredit as your Java source editor, you can prevent the tab character from being saved by using the following procedure, by Ultredit 2 spaces in the length of the tab used in the first room, and then using the format| The Tabs to Spaces menu converts Tab to spaces.
- Page width
The page width should be set to 80 characters. The source code generally does not exceed this width and results in a complete display, but this setting can also be flexibly adjusted. In any case, an extra long statement should be folded after a comma or an operator. When a statement is folded, it should be indented 2 characters more than the original statement.
- {} to
The statement in {} should be used as a single line. For example, the 1th line below is wrong, and line 2nd is correct:
If the statement should be indented to the relative position of the {line corresponding to it.
- Brackets
There should be no spaces between the opening parenthesis and the last character, and no spaces should appear between the closing parenthesis and the previous character. The following example illustrates the errors and proper use of parentheses and spaces:
Callproc (Aparameter); Error
Callproc (Aparameter); That's right
Do not use meaningless parentheses in the statement. Parentheses should only appear in the source code for some purpose. The following example illustrates the error and correct usage:
if ((I) = 42) {//error-Bracket meaningless
if (I = =) or (J = =) then//correct-does require parentheses
Code of Procedure writing
- Exit ()
Exit should not be invoked except in main, where it can be invoked. Because this does not give any code code an opportunity to intercept the exit. A similar background service program should not exit because a library module decides to quit.
- Abnormal
The declared error should throw a runtimeexception or a derived exception.
The main () function at the top level should intercept all exceptions and print (or record in a log) on the screen.
- Garbage Collection
Java uses sophisticated background garbage collection techniques in place of reference counts. But this can lead to a problem: you have to do the clearing after you have used an instance of the object. For example, a Prel programmer might write this:
... { fileoutputstream fos = new FileOutputStream (projectfile); project.save (FOS, IDE project File); }
unless the output stream is turned off as a scope, the unreferenced program language, such as Java, does not automatically complete the task of clearing variables. Must be written as follows:
fileoutputstream fos = new FileOutputStream (projectfile);
project.save (FOS, IDE project File); fos.close ();
- Final class
Never define a class as final for performance reasons (unless the program's framework requires it)
If a class is not ready to be inherited, it is best to note it in the class document, rather than defining her as final. This is because no one can guarantee that she will be inherited for any reason.
Programming Skills
- byte array conversion to characters
To convert a byte array to characters, you can do this:
"Hello world!". GetBytes ();
- Utility class
The Utility class (a class that simply provides a method) should be declared abstract to prevent inheritance or initialization.
- Class
The following code is a good way to initialize an array:
objectarguments = new object[] {arguments};
- Enum type
JAVA support for enumerations is not good, but the following code is a useful template:
Class Colour {public static final colour black = new Colour (0, 0, 0); public static final Colour RED = new Colour (0xFF, 0, 0); public static final Colour GREEN = new Colour (0, 0xFF, 0); public static final Colour BLUE = new Colour (0, 0, 0xFF); public static final colour white = new Colour (0xFF, 0xFF, 0xFF);}
This technique implements constants such as red, GREEN, BLUE, and so on that can be used as enumerated types in other languages. They can be compared using the ' = = ' operator.
But there is a flaw in this use: If a user uses this method to create a color black
New Colour (0,0,0)
So this is another object, and the ' = = ' operator will produce an error. Her equal () method is still valid. For this reason, the flaw in this technique is best noted in the document, or only in its own package.
Swing
- Avoid using AWT components
- Mix AWT and Swing components
Use caution if you want to mix AWT components with Swing components. In fact, try not to mix them up and use them.
- Scrolled AWT Component
The AWT component should never use the JScrollPane class to implement scrolling. Be sure to use the AWT ScrollPane component when scrolling AWT components.
- Avoid using AWT components in the Internalframe component
Try not to do so, otherwise there will be unexpected consequences.
- Z-order problem
AWT components are always displayed on top of Swing components. Be careful when using the pop-up menu containing AWT components, and try not to use it this way.
Debugging
- Debugging is a very important part of software development, and it exists in every part of the software lifecycle. Debugging can be configured to open, close is the most basic.
A common debugging method is to use a PrintStream class member, NULL when no debug stream is defined, and a class to define a debug method to set the stream for debugging.
Performance
- When writing code, you should consider performance issues from beginning to finish. This is not to say that time should be wasted on optimizing code, but that we should always remind ourselves to be aware of the efficiency of the Code. For example: If there is no time to implement an efficient algorithm, then we should record it in the document so that we can implement it later when we are free.
Not everyone agrees that you should optimize performance when writing code, and they think that the problem of performance optimization should be considered later in the project, after the outline of the program has been implemented.
- Unnecessary construction of objects
- Do not construct and dispose of objects in loops
- Using the StringBuffer object
Use the StringBuffer class as much as possible when working with strings, and the StringBuffer class is the basis that forms the string class. The String class encapsulates the StringBuffer class and provides a secure interface for developers (at the cost of more time). When we construct strings, 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 constantly add many characters to complete the construct, then we should use the StringBuffer object and her append () method. If we use a String object instead of a StringBuffer object, it will cost a lot of unnecessary CPU time to create and release the object.
- Avoid too much use of the Synchronized keyword
Avoid unnecessary use of keyword synchronized, you should use her when necessary, this is a good way to avoid deadlock.
Portability
Borland Jbulider don't like synchronized this keyword, if your breakpoint is set in the scope of these keywords, when debugging you will find the breakpoint will jump around, let you at a loss. Try not to use it unless you have to.
- Line Wrap
If you need to change lines, try to use println instead of "\ n" in the string.
You don't do this:
System.out.print ("hello,world!\n");
To do this:
System.out.println ("hello,world!");
Or you can construct a string with a newline character, at least like this:
String newline = system.getproperty ("Line.separator");
System.out.println ("Hello World" + newline);
- PrintStream
PrintStream has been disapproved (deprecated) and used printwrite to replace her.
reference materials
- Find information about other aspects of the Thread class and Java 2 platform, Standard Edition, API specification.