I. Purpose
ForCodeFirst, it must be correct and can followProgramThe second requirement is that the Code must be clear and understandable, so that other programmers can easily understand the actual work of the Code. In the field of software engineering, the uniform style of source programs marks maintainability and readability, and is an important part of software projects. At present, there is no written coding style document, so many times, programmers do not have a common standard to comply with, the encoding style is different, the program has poor maintainability and readability. By establishing code writing specifications, a Development Group coding convention is formed to improve the reliability, readability, modification, maintainability, inheritance and consistency of the program, and ensure the quality of the program code, inherit the software development results and make full use of resources to share the work results between developers.
Based on the existing coding style in the industry, this article describes a JBuilder-based project style and strives for a unified programming style, it also describes the overall encoding style, code file style, function writing style, variable style, and comment style. (These specifications are not always strictly observed, but must make the program readable)
Ii. Overall encoding Style
1. indent
We recommend that you use four spaces for indentation. We recommend that you set the block ident of the editor page to 4 and the tab size to 8 in tools/Editor options. Pre-processing statements, global data, titles, additional descriptions, function descriptions, and labels are written in the top level. The & quot ;{& quot;, & quot ;}& quot; pairs of statement blocks are aligned with the previous line. We recommend that each & quot; {& quot;, & quot ;}& quot; occupies a single row to facilitate matching. The default method in JBuilder is start & quot ;{& quot; not a single row, we recommend that you change the format to the above (set braces to next line in code style in Project/default project properties ).
2. Space
In principle, variables, classes, constant data, and functions are of the type, with appropriate spaces between modifier names, and are aligned as needed. If. The space rules of the operators are as follows: & quot;, & quot;->; & quot;, & quot; [& quot;, & quot;] & quot;, & quot; ++ & quot;, & quot; -- & quot;, & quot ;~ & Quot;, & quot ;! & Quot;, & quot; + & quot;, & quot;-& quot; (positive and negative signs), & quot; & amp; & quot; (Reference) do not add spaces on both sides of these operators (where the single object operator refers to the side connected to the operand), and other operators (including most of the binary operators and the three object operator & quot ;? : & Quot; add a space on both sides. when defining a function, you can use multiple null or non-empty spaces to align it. This is not required for function implementation. & Quot;, & quot; the operator only has one space after it. When alignment is required, it can be left blank or with multiple spaces. Whether there are Parentheses or not, use spaces to separate the comments added after the statement line and align them as much as possible. I personally think that this item can be followed or not according to my habits.
3. Alignment
In principle, closely related rows should be aligned. alignment includes type, modifier, name, and parameter alignment. In addition, the length of each line should not exceed the screen length. If necessary, wrap the line. When changing the line, try to place at & quot;, & quot; or operator. it is best to start with an operator after wrapping, and the following lines are indented at the first line of the statement, but the statement is still indented at the first line, that is, the next line is "{" should be aligned with the first line.
It is best to add spaces to form alignment for variable definitions. It is best to put variables of the same type together. For example:
Int value;
Int result;
Int length;
DWORD size;
DWORD bufsize;
I personally think that this item can be followed or not according to my habits.
4. Empty rows
Empty rows without rules, for example, ten consecutive empty rows. There are two blank lines between the parts of the program file structure. If it is not necessary, only one line can be blank. Generally, two lines are empty between function implementations. Because each function also has function description comments, therefore, only one or no blank row is required, but at least one row should be blank if no function description is available. We recommend that you add "// ------" to separate your own functions. There should be at least one line of data in the function and at least one line of code should be empty in the Code. We recommend that you leave a blank line before the variable declaration in the code. There must be at least one line between the four "P" in the class, and there should also be a blank line between the data and the function.
5. Notes
Annotations are a concrete manifestation of software readability. Program comments generally account for 20% of program code, and the software engineering requirement is not less than 20%. Program annotations cannot be expressed in abstract languages. Computer abstraction languages such as & quot; Processing & quot; and & quot; loop & quot; must accurately express the processing instructions of programs. For example: & quot; calculate the net Demand & quot; and & quot; Calculate the processing time of the first process & quot. Avoid comments for each program line. You can add comments before a program to have a clear processing logic.
Comments are indispensable, but they should not be too many. Do not passively write comments for writing comments. There are four necessary Annotations:
A. Title and additional instructions.
B. Descriptions of functions and classes. Almost every function should be properly described. Generally, before function implementation, if function implementation is absent, it is added before the function prototype. The main content is the function, purpose,AlgorithmParameter description, return value description, and other descriptions, such as special software and hardware requirements. Declarations of Public Functions and public classes must be annotated to describe their usage methods and design ideas. Of course, choosing the appropriate naming format can help you better understand things.
C. The code is unclear or cannot be transplanted.
D. and a small number of other annotations, such as the comments of custom variables and the code writing time.
There are two types of Annotations: & quot;/**/& quot; and & quot; // & quot; we recommend that you use block annotations for, d. Use line comments. B and C are based on the situation, but they should be unified. B and C should be in the form of class B Comments in at least one unit. The annotations for different files and structures are described in detail later.
6. Code Length
For each function, we recommend that you set the code length to about 53 lines. Code with more than 53 lines should be split into two or more functions. The function splitting rules should be based on the original algorithm and the split parts should be reusable. For repetitive code used in multiple modules or forms, you can create a function with a public nature and place it in a public module.
7. Page width
The page width should be set to 80 characters.Source codeGenerally, it will 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.
8. Number of rows
In a general integrated programming environment, each screen can only display a program of no more than 50 lines. Therefore, this function is usually displayed on 5-6 screens. in some environments, it takes about 8 screens to be displayed. In this way, it will be difficult to read or modify the program. Therefore, we recommend that you extract the program blocks that have completed relatively independent functions into a single function. Extract the program blocks that have completed the same or similar functions as independent subfunctions. It can be found that the more upper-layer functions, the easier it is to call several subfunctions. the more detailed the underlying functions are, the more specific the work is. This is a sign of a good program. In this way, we can easily control the logic of the entire program in the upper-layer functions, and focus on the implementation of some functions in the underlying functions.
Iii. Code File Style
All Java (*. Java) files must comply with the following style rules:
. File generation
For standard Java Derived classes, use JBuilder's object gallery tool to generate file formats, avoiding manual header files/implementation files.
. Package/import
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.
. File Header comment
The comments in the file header mainly indicate some information about the file, which is the general description of the program and can enhance the readability and maintainability of the program. The file header comment is generally placed after the package/imports statement and before the class description. At least the file name, creator, Creation Time, and content description must be written. In the code generated by JBuilder's object gallery tool, annotations are automatically added in the class and project files. We also need to add some annotations. The format should be as follows:
/**
* Title: determines the mouse position
* Description: determines the job field in which the mouse is currently located and returns the job number.
* @ Copyright: Copyright (c) 2002
* @ Company: Hit
* @ Author: rivershan
* @ Version: 1.0
* @ Time: 2002.10.30
*/
. 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
. 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.
. 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. (I personally think that it should be written by branch whenever possible)
/**
* 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;
}
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 ).
Access type (& quot; Public & quot;, & quot; Private & quot;, etc .) and any & quot; static & quot;, & quot; Final & quot; or & quot; synchronized & quot; 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.
Public
Counterset (INT size)
{
This. size = size;
}
. Clone Method
If this class can be cloned, the next step is the clone method:
Public
Object clone ()
{
Try
{
Counterset OBJ = (counterset) Super. Clone ();
OBJ. packets = (INT []) packets. Clone ();
OBJ. size = size;
Return OBJ;
}
Catch (clonenotsupportedexception E)
{
Throw new internalerror (& quot; unexpected clonenotsupportedexception: & quot;
+ E. getmessage ());
}
}
. Class Method
The following describes how to write a class:
/**
* Set the packet counters
* (Such as when restoring from a database)
*/
Protected final
Void setarray (INT [] R1, int [] R2, int [] R3, int [] R4)
Throws illegalargumentexception
{
//
// Ensure the arrays are of equal size
//
If (r1.length! = R2.length | r1.length! = R3.length | r1.length! = R4.length)
Throw new illegalargumentexception (& quot; arrays must be of the same size & quot ;);
System. arraycopy (R1, 0, R3, 0, r1.length );
System. arraycopy (R2, 0, R4, 0, r1.length );
}
. Tostring Method
In any case, each class should define the tostring method:
Public
String tostring ()
{
String retval = & quot; counterset: & quot ;;
For (INT I = 0; I <data. Length (); I ++)
{
Retval + = data. bytes. tostring ();
Retval + = data. packets. tostring ();
}
Return retval;
}
. Main Method
If the main (string []) method has been defined, it should be written at the bottom of the class.
Iv. Function Writing Style
. Function Name
Generally, the name of a function is based on the principle that it can express the meaning of a function's action. Generally, it is triggered by a verb and followed by a noun representing an action object. The first letter of each word should be capitalized. In addition, there are some general rules for function naming. If the number is obtained, the GET header is used to keep up with the name of the object to be retrieved. If the number is set, the set header is used to keep up with the name of the object to be set; the function in the object that responds to the message for action can be named on and then the corresponding message name. The function that performs the active action can be named do, and then the corresponding action name. There are many other similar rules. Programmers need to read more excellent programs and accumulate experience to make good function naming.
. Function Annotation
Functions automatically generated by the system, such as mouse action response functions, do not need to be commented out or explained too much;
For a self-compiled function, if it is a key function of the system, the information of the function must be indicated at the top of the function implementation section. The format is as follows:
/**
* Function Name:
* Prepared:
* References:
* Functions:
* Input parameters:
* Output parameters:
* Secondary note:
*/
Try to follow the above format.
V. Symbolic Style
. General requirements
There is a common point for the definition of various symbols, that is, we should use practical English words or abbreviations of English words. Do not use simple but meaningless strings, do not use Arabic numerals as much as possible. Do not use the first letter of Chinese pinyin. Such names are not recommended: value1, value2, value3, value4 ....
For example:
File, code, Data, pagepoint, faxcode, address, bank ),......
. Variable name
Variable naming is composed of (prefix + modifier. Currently, it is quite popular to use a set of naming rules that are first used by a Microsoft Hungarian software engineer and popularized at Microsoft. Now they are called the Hungarian naming rules. According to the Hungarian naming law, lowercase abbreviations of the variable type corresponding to the identifier are used as the prefix of the identifier, followed by English words or abbreviations indicating the meaning of the variable. The following are some naming methods in the Hungarian naming method:
(1) lifetime modification: L (local) is used to represent the local variable, P (public) is used to represent the global variable, and S (send) is used to represent the parameter variable.
(2) type modification: the string is represented by S (ansistring), C (char), n (number), I (intger), and D (double) double precision, F (float) floating point type, B (bool) boolean type, D (date) indicates date type.
For example:
Li_length indicates the integer local variable, which is used to identify the length. ls_code indicates the linear local variable and is used to identify the code.
. Control name
The control name is composed of (prefix + modifier. The prefix is the name of the control.
Button variable buttons + xxxxxxx such as buttonsave, buttonexit, and buttonprint
Label + XXXXXXXX, such as labelname and labelsex
Data Table variable table + xxxxxx such as tablefile and tablecount
Query variable + xxxxxx For example: queryfile, queryceneter, etc.
Data Source variables datasource + XXX such as performancefile and performancecenter
................
(Note: it is best to directly use the table name for the "modifier" section of the table-related control .)
. Package name
The package name must be a lowercase word.
. Class Name
The name of a class must begin with one or more uppercase letters that can express the meaning of the class, and all other letters are lowercase words or abbreviations, so that the name of the class can be understood more easily.
. Class variable name
The variable name must start with a lowercase letter. The following words start with an uppercase letter. For the member variables of the class, when naming their identifiers, you must add the prefix M _ representing the member (member _. For example, if an identifier is m_dwflag, the variable it represents is a member variable of the double type, and it represents a flag.
Name of the. Static final variable
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:
Byte [] buffer;
Instead:
Byte buffer [];
. Method parameters
Use meaningful parameter names. If possible, use the same name as the field to be assigned values:
Setcounter (INT size)
{
This. size = size;
}
. Mysterious number
First, we need to talk about what a mysterious number is. We often use some quantities in programs, which have specific meanings. For example, if we write a salary statistics program with 50 employees, we will use the number 50 in the program to perform various operations. Here, 50 is & quot; mysterious number & quot ;. Why is it mysterious? Because other programmers see the number 50 in the program and do not know its meaning, they can only guess.
The appearance of the mysterious number in the program will reduce the readability of the program. Avoid it as much as possible. The solution is to define a mysterious number as a constant. Note that the name of this constant should be able to express the meaning of this number, and should all be capitalized to distinguish it from the identifier corresponding to the variable. For example, the number 50 above can be defined as a constant named numofemployees. In this way, other programmers can easily understand the program.
6. programming style
. 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:
...
{
Fileoutputstream Fos = new fileoutputstream (projectfile );
Project. Save (FOS, & quot; ide project file & quot ;);
}
...
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:
Fileoutputstream Fos = new fileoutputstream (projectfile );
Project. Save (FOS, & quot; ide project file & quot ;);
FOS. Close ();
. Clone
The following is a useful method:
Implements cloneable
Public
Object clone ()
{
Try
{
Thisclass OBJ = (thisclass) Super. Clone ();
OBJ. field1 = (INT []) field1.clone ();
OBJ. field2 = field2;
Return OBJ;
}
Catch (clonenotsupportedexception E)
{
Throw new internalerror (& quot; unexpected clonenotsupportedexception: & quot; + E. getmessage ());
}
}
. Final class
Never define a class as final for performance reasons (unless required by the framework of the program)
If a class is not ready to be inherited, it is best to specify it in the class document rather than define it as final. This is because no one can guarantee that she will be inherited for any reason.
Member variables of the. Category class
Most of the class member variables should be defined as protected to prevent the inherited class from using them.
Note: Use & quot; int [] packets & quot; instead of & quot; int Packets [] & quot;. The latter is never used.
Public void setpackets (INT [] packets)
{
This. packets = packets;
}
Counterset (INT size)
{
This. size = size;
}
. Byte array to characters
To convert byte arrays to characters, you can do this:
& Quot; Hello world! & Quot;. getbytes ();
. Utility Class
Utility classes (classes that only provide methods) should be declared abstract to prevent inheritance or initialization.
. Initialization
The following code is a good method for initializing Arrays:
Objectarguments = new object []
{
Arguments
};
. Enumeration type
Java does not support enumeration well, 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 technology implements red, green, blue, and other constants that can be used as enumeration types in other languages. They can be compared using the '=' operator.
However, this method has a defect: if a user uses this method to create a color black
New colour (0, 0)
This is another object. The '=' operator produces an error. Her equal () method is still valid. For this reason, it is best to indicate the technical defects in the document or use them only in your own package.
. Hybrid use of AWT and swing Components
Be careful when mixing the AWT and swing components. In fact, try not to mix them together.
. Rolling AWT component
The AWT component must not use the jscrollpane class for scrolling. The AWT scrollpane component must be used for Rolling AWT components.
. Avoid using the AWT component in the internalframe component.
Do not do this as much as possible. Otherwise, unexpected consequences may occur.
. Z-order
The AWT component is always displayed on the swing component. When using the pop-up menu containing the AWT component, be careful not to use it like this.
8. Performance
When writing code, you should consider performance issues from the beginning to the end. This does not mean that time should be wasted on code optimization, but we should always remind ourselves to pay attention to code efficiency. For example, if you don't have time to implement an efficient algorithm, you should record it in the document so that you can implement it when you are free.
Not all people agree that the performance should be optimized when writing code. They believe that the performance optimization problem should be considered later in the project, that is, after the outline of the program has been implemented.
. Unnecessary Object Construction
Do not create or release objects in a loop
. Use 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 her 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.
. Avoid using too many synchronized keywords.
Avoid unnecessary use of the keyword synchronized and use it again when necessary. This is a good way to avoid deadlocks.
Rivershan original