Java Language Coding Specification
1 Scope
This specification specifies rules and recommendations for typography, annotation, naming, encoding, and JTEST when programming in the Java language.
This specification applies to products and projects programmed using the Java language.
2. Normative references
The terms in the following documents become the terms of this specification by reference in this specification. For dated reference documents, all subsequent amendments (excluding errata content) or revisions do not apply to this specification, however, parties to agreements based on this specification are encouraged to study whether the latest versions of these documents can be used . For undated references, the latest version applies to this specification.
3. Terms and Definitions
Rules: The principles that must be followed when programming.
Advice: Principles that must be considered when programming.
Format: A description of the format for this specification.
Explanation: Provide necessary explanations for this specification or recommendation.
Example: Give examples of both positive and negative aspects of this specification or recommendation.
4. Typesetting specifications
4.1. Rules
4.1.1. *Program blocks should be written in an indented style, and the number of indented spaces is 4.
Description: There can be inconsistencies in the code automatically generated by the development tools.
4.1.2. *Delimiters (such as curly braces '{' and '}') should be on a separate line and in the same column, and left-aligned with the statement that refers to them. At the beginning of the function body, the definition of classes and interfaces, and the programs in the if, for, do, while, switch, and case statements must adopt the above indentation method.
Example: The following example does not conform to the specification.
for (...) {
... // program code
}
if (...)
{
... // program code
}
void example_fun( void )
{
... // program code
}
should be written as follows:
for (...)
{
... // program code
}
if (...)
{
... // program code
}
void example_fun( void )
{
... // program code
}
4.1.3. *Longer statements, expressions or parameters (>80 characters) should be written in multiple lines, long expressions should be divided into new lines at the place of low priority operators, and operators should be placed before new lines First of all, the new line should be properly indented to make the typesetting neat and the statement readable.
Example:
if (filename != null
&& new File(logPath + filename).length() < LogConfig.getFileSize())
{
... // program code
}
public static LogIterator read(String logType, Date startTime, Date endTime,
int logLevel, String userName, int bufferNum)
4.1.4. *It is not allowed to write multiple short statements in one line, that is, only write one statement in one line.
Example: The following example does not conform to the specification.
LogFilename now = null; LogFilename that = null;
should be written as follows:
LogFilename now = null;
LogFilename that = null;
4.1.5. *If, for, do, while, case, switch, default and other statements occupy one line, and the execution statements of if, for, do, while and other statements must be enclosed in brackets {} no matter how many.
Example: The following example does not conform to the specification.
if(writeToFile) writeFileThread. interrupt();
should be written as follows:
if(writeToFile)
{
writeFileThread. interrupt();
}
4.1.6. *Blank lines must be added between relatively independent program blocks and after variable descriptions.
Example: The following example does not conform to the specification.
if(log.getLevel() < LogConfig.getRecordLevel())
{
return;
}
LogWriter writer;
should be written as follows:
if(log.getLevel() < LogConfig.getRecordLevel())
{
return;
}
LogWriter writer;
int index;
4.1.7. *Alignment only uses the space bar, not the TAB key.
Explanation: When reading the program with different editors, the layout of the program is not neat due to the different number of spaces set by the TAB key. Editing environments such as JBuilder and UltraEdit support the replacement of tabs at the beginning of lines with spaces, and this option should be turned on.
4.1.8. *When performing equivalent operations on two or more keywords, variables, and constants, spaces must be added before, after, or before and after the operators between them; when performing non-equivalent operations, if it is a relationship Close immediate operators (such as .) should not be followed by spaces.
Explanation: The purpose of writing code in this loose way is to make the code more clear.
Since the clarity produced by leaving spaces is relative, there is no need to leave spaces in sentences that are already very clear. If the statement is clear enough, there is no need to add spaces inside the parentheses (that is, after the left parenthesis and before the right parenthesis). There is no need to add spaces between multiple brackets, because brackets are already the clearest sign in the Java language.
In long sentences, if you need to add a lot of spaces, you should keep the overall clarity and not add spaces locally. When leaving spaces for operators, do not leave more than two spaces in a row.
Example:
(1) Commas and semicolons are only followed by spaces.
int a, b, c;
(2) Comparison operators, assignment operators "=", "+=", arithmetic operators "+", "%", logical operators "&&", "&", bit field operators "<<", Add spaces before and after binary operators such as "^".
if (current_time >= MAX_TIME_VALUE)
a = b + c;
a \*= 2;
a = b^2;
(3) "!", "~", "++", "--", "&" (address operator) and other unary operators do not add spaces before and after.
flag = !isEmpty; // between non-operating "!" and content
i++; // Between "++", "--" and content
(4) There are no spaces before and after ".".
p.id = pid; // no spaces before and after "."
(5) Spaces should be added between if, for, while, switch, etc. and the following brackets to make keywords such as if more prominent and obvious.
if (a >= b && c > d)
4.2. Recommendations
Class attributes and class methods should not be cross-placed, and attributes or methods with different access ranges should not be cross-placed as much as possible.
Format:
class definition
{
Class public property definition
Class protected attribute definition
Class private property definition
Class public method definition
Class protected method definition
Class private method definition
}
5. Comment specification
5.1. Rules
5.1.1. Under normal circumstances, the amount of effective comments in the source program must be more than 30%.
Explanation: The principle of comments is to help the reading and understanding of the program. Add them where they should be added. Comments should not be too many or too few. The comment language must be accurate, easy to understand, and concise. You can use the annotation statistics tool to count.
5.1.2. Package comments: Package comments are written into an HTML format specification file named package.html and placed in the current path.
Description: Convenient for JavaDoc collection
Example:
com/huawei/msg/relay/comm/package.html
5.1.3. Note content of the package: brief description of the function of the package, detailed description of the content of the package, product module name and version, and company copyright.
Description: The function of this package and its position in the whole project should be explained in the detailed description.
Format:
<html>
<body>
<p>A one-sentence summary.
<p>Detailed description.
<p>Product module name and version
<br>Company copyright information
</body>
</html>
Example:
<html>
<body>
<P>Provide the communication class for Relay, and the upper layer business uses the communication class of this package to communicate with SP.
<p>Detailed description. . . . . . . .
<p>MMSC V100R002 Relay
<br>(C) Copyright 2002-2007 VanceInfo Technology Co., Ltd.
</body>
</html>
5.1.4. File comment: The file comment is written in the file header, before the package name.
Note: Be careful to start with /* to avoid being collected by JavaDoc
Example:
/*
* Note content
*/
package com.huawei.msg.relay.comm;
5.1.5. File annotation content: copyright statement, description information, generation date, modification history.
Description: The filename is optional.
Format:
/*
* Filename: [filename]
* Copyright: <Copyright>
* Description: <description>
* Modified by: <modified by>
* Modified time: YYYY-MM-DD
* Modification order number: <modification order number>
* Modification content: 〈Modification content〉
*/
Note: After each modification, write the modification information in the header of the file, and you can directly paste the blue font information to the VSS comment during CheckIn. Can be dispensed with until the code is under control.
Example:
/*
* File name: LogManager.java
* Copyright: Copyright 2002-2007 Huawei Tech. Co. Ltd. All Rights Reserved.
* Description: MMSC V100R002 Relay general logging system
* Modified by: Zhang San
* Modification time: 2001-02-16
* Modifications: Added
*Modified by: Li Si
* Modification time: 2001-02-26
* Modification number: WSS368
* Modification content: . . . . . .
*Modified by: Wang Wu
* Modification time: 2001-03-25
* Modification number: WSS498
* Modification content: . . . . . .
*/
5.1.6. Class and interface comments: This comment is placed after the package keyword and before the class or interface keyword.
Description: Convenient for JavaDoc collection.
Example:
package com.huawei.msg.relay.comm;
/**
* Note content
*/
public class CommManager
5.1.7. Contents of class and interface comments: class comments are mainly a one-sentence brief description of the function and a detailed description of the function.
Description: It can be listed as needed: version number, generation date, author, content, function, relationship with other classes, etc. If a class has bugs, be honest about those bugs.
Format:
/**
* 〈A brief description of the function in one sentence〉
* 〈Detailed function description〉
* @author [author]
* @version [version number, YYYY-MM-DD]
* @see [related class/method]
* @since [product/module version]
* @deprecated
*/
Description: The description part explains the functions, functions, usage methods and precautions of the class or interface. After each modification, the author and update version number and date are added. @since means that this class or interface has existed since that version, @deprecated means This class or interface is deprecated.
Example:
/**
* The LogManager class centrally controls the operation of reading and writing logs.
* All are static variables and static methods, providing a unified interface to the outside world. Allocate the reader/writer corresponding to the log type,
* Read or write log records that meet the conditions.
*
* @author Zhang San, Li Si, Wang Wu
* @version 1.2, 2001-03-25
* @see LogIteraotor
* @see BasicLog
* @since CommonLog1.0
*/
5.1.8. Class attributes, public and protected method comments: write on the class attributes, public and protected methods.
Example:
/**
* Note content
*/
private String logType;
/**
* Note content
*/
public void write()
5.1.9. Member variable comment content: the meaning, purpose, function, and possible use of member variables.
5.1.10. Public and protected method comment content: List the one-sentence function description, detailed function description, input parameters, output parameters, return value, exception, etc. of the method.
Format:
/**
* 〈A brief description of the function in one sentence〉
* 〈Detailed function description〉
* @param [parameter 1] [parameter 1 description]
* @param [parameter 2] [parameter 2 description]
* @return [return type description]
* @exception/throws [type of exception] [description of exception]
* @see [class, class#method, class#member]
* @deprecated
*/
Explanation: @since means that this method has been available since that version; @exception or throws lists the exceptions that may still occur; @deprecated means that this method is not recommended.
Example:
/**
* Read logs according to log type and time.
* Allocate the LogReader corresponding to the log type, specify the type, query time period, condition and number of repeater buffers,
* Read log records. If the query condition is null or 0, it means unlimited, and if the number of repeater buffers is 0, the log cannot be read.
* The query time is left-inclusive, that is, [startTime, endTime) .
* @param logTypeName log type name (defined in the configuration file)
* @param startTime query log start time
* @param endTime the end time of the query log
* @param logLevel query log level
* @param userName query the user's log
* @param bufferNum log repeater buffer record number
* @return result set, log repeater
* @since CommonLog1.0
*/
public static LogIterator read(String logType, Date startTime, Date endTime,
int logLevel, String userName, int bufferNum)
5.1.11. For the exception thrown by the throw statement inside the method, it must be marked in the comment of the method. For the exception thrown by other methods called, choose the main one to explain in the comment. For non-RuntimeException, that is, the exception that the throws clause declares will be thrown, it must be marked in the comment of the method.
Note: Exception annotations are represented by @exception or @throws, which are equivalent in JavaDoc, but it is recommended to use @exception to mark Runtime exceptions, and @throws to mark non-Runtime exceptions. The exception comment must explain the meaning of the exception and the conditions under which the exception is thrown.
5.1.12. *The comment should be close to the code it describes, and the comment to the code should be placed above it or adjacent to the right (comment for a single statement), and cannot be placed below it. If it is placed above it, it needs to be Separate it from the code above it with a blank line.
5.1.13. *Comments are indented the same as the content described.
Description: It can make the typesetting of the program neat, and facilitate the reading and understanding of the notes.
Example: In the following example, the typesetting is not neat, and it is a little inconvenient to read.
public void example( )
{
// comment
CodeBlockOne
// comment
Code Block Two
}
Should be changed to the following layout.
public void example( )
{
// comment
CodeBlockOne
// comment
Code Block Two
}
5.1.14. *Separate the comment from the code above it with a blank line.
Example: The following example shows that the code is too compact.
// comment
program code one
// comment
program code two
should be written as follows:
// comment
program code one
// comment
program code two
5.1.15. *Comments must be written on variable definitions and branch statements (conditional branches, loop statements, etc.).
Explanation: These statements are often the key to a program to achieve a specific function. For maintainers, good comments help to better understand the program, sometimes even better than reading design documents.
5.1.16. *For the case statement under the switch statement, if it is necessary to process a case and enter the next case processing due to special circumstances, a clear comment must be added before the next case statement after the case statement is processed .
Explanation: In this way, the intention of the program writer is clearer, and it can effectively prevent the break statement from being omitted for no reason.
5.1.17. *Comment while writing the code, modify the code and modify the corresponding comment at the same time to ensure the consistency of the comment and the code. Comments that are no longer useful are deleted.
5.1.18. *The content of the comment should be clear, clear, and accurate in meaning to prevent ambiguity in the comment.
Explanation: Incorrect comments are not helpful but harmful.
5.1.19. *Avoid using abbreviations in comments, especially uncommon abbreviations.
Explanation: Before using an abbreviation, the abbreviation should be explained as necessary.
5.2. Recommendations
5.2.1. *Avoid inserting comments in the middle of a line of code or expression.
Note: Unless necessary, comments should not be inserted in the middle of the code or expression, otherwise it will easily make the code less understandable.
5.2.2. *By correctly naming functions or procedures, variables, structures, etc. and organizing the structure of the code reasonably, the code becomes self-commenting.
Description: Clear and accurate naming of functions, variables, etc. can increase code readability and reduce unnecessary comments.
5.2.3. *Annotate at the function and intent level of the code to provide useful and additional information.
Explanation: The purpose of the comment is to explain the purpose, function and method of the code, provide information other than the code, help readers understand the code, and prevent unnecessary repetition of comment information.
Example: The following comments do not make much sense.
// if receiveFlag is true
if (receiveFlag)
The following comments give additional useful information.
// if a message was received from the link
if (receiveFlag)
5.2.4. *Add a comment mark to the right of the end line of the program block to indicate the end of a certain program block.
Note: When the code segment is long, especially when multiple nesting, doing so can make the code clearer and easier to read.
Example: See the example below.
if (...)
{
program code1
while (index < MAX_INDEX)
{
program code2
} // end of while (index < MAX_INDEX) // indicates the end of the while statement
} // end of if (...) // indicates which if statement ends
5.2.5. *Comments should consider the factors of program readability and appearance typesetting. If the language used is both Chinese and English, it is recommended to use Chinese, unless it can be expressed in very fluent and accurate English.
Note: The comment language is not uniform, which will affect the legibility and appearance of the program. For maintenance reasons, it is recommended to use Chinese.
5.2.6. Single-line comments in methods use //.
Note: It is convenient to use /* when debugging the program. . . */ Comment out a long program.
5.2.7. Notes Use Chinese notes and Chinese punctuation as much as possible. The first sentence of the method and class description should try to use concise and clear words to summarize the function, and then add a period. The following sections can be described in detail.
Note: When the JavaDoc tool collects introductions, it is used to select the first sentence.
5.2.8. Description of the sequential implementation process Use 1, 2, 3, 4 to comment in front of the code of each implementation step.
Example: The following is a process comment for setting properties
//1. Determine whether the input parameters are valid.
. . . . .
// 2. Set local variables.
. . . . . .
5.2.9. Some complicated codes need to be explained.
Example: This is mainly an explanation of the leap year algorithm.
//1. If it is divisible by 4, it is a leap year;
//2. If it is divisible by 100, it is not a leap year.;
//3. If it is divisible by 400, it is a leap year..
6. Naming convention
6.1. Rules
6.1.1. The package name adopts the inverted domain suffix plus the custom package name, using lowercase letters. The range of package names should be planned within the department to prevent conflicts. Products within a department use the name of the department plus the module name. Products of a product line use the name of the product plus the name of the module.
Format:
com.huawei.product name.module name
com.huawei.department name.project name
Example:
Relay module package name com.huawei.msg.relay
Common log module package name com.huawei.msg.log
6.1.2. Class names and interfaces use English descriptions with complete class meanings. The first letter of each English word is capitalized and the rest of the letters are lowercased.
Example:
OrderInformation, CustomerList, LogManager, LogConfig
6.1.3. The method name uses an English description with complete class meaning: the first letter of the word is lowercase, and the first letter of the remaining words is capitalized, and the remaining letters are lowercase.
Example:
private void calculateRate();
public void addNewOrder();
6.1.4. In the method, the method of accessing the attribute adopts the setter and getter method, and the action method adopts the verb and the verb-object structure.
Format:
get + non-boolean property name()
is + boolean attribute name()
set + property name()
verb()
verb + object()
Example:
public String getType();
public boolean isFinished();
public void setVisible(boolean);
public void show();
public void addKeyListener(Listener);
6.1.5. The attribute name uses English description with complete meaning: the first letter of the word is lowercase, and the first letter of the remaining words is capitalized, and the remaining letters are lowercase. Property names cannot be the same as method names.
Example:
private customerName;
private orderNumber;
private smpSession;
6.1.6. The constant name is described in English in all uppercase, and English words are separated by underscores, and are modified with final static.
Example:
public final static int MAX_VALUE = 1000;
public final static String DEFAULT_START_DATE = "2001-12-08";
6.1.7. The attribute name can be the same as the public method parameter, but not the same as the local variable. Use this reference when referring to non-static member variables, and use class name reference when referencing static member variables.
Example:
public class Person
{
private String name;
private static List properties;
public void setName (String name)
{
this.name = name;
}
public void setProperties (List properties)
{
Person.properties = properties;
}
}
6.2. Recommendations
6.2.1. Commonly used component classes are named after the component name plus the component type name.
Example:
Application type, the name ends with App - MainApp
Frame type, the name ends with Frame - TopoFrame
For Panel type, it is recommended to end the name with Panel——CreateCircuitPanel
Bean type, it is recommended that the name end with Bean - DataAccessBean
For EJB type, it is recommended to end the name with EJB - DBProxyEJB
For the Applet type, it is recommended that the name end with Applet——PictureShowApplet
6.2.2. If the function name exceeds 15 letters, you can use the method of removing vowels or abbreviate the function name in the abbreviation method that is customary in the industry.
Example:
getCustomerInformation() changed to getCustomerInfo()
6.2.3. Accurately determine the access control symbols of member functions. It is not necessary to use public attributes, please use protected. It is not necessary to use protected, please use private.
Example:
protected void setUserName(), private void calculateRate()
6.2.4. When naming attributes with collective meanings, try to include their plural meanings.
Example:
customers, orderItems
7. Coding Standards
7.1. Rules
7.1.1. *Clarify the function of the method, and realize the method design precisely (rather than approximately). A function only completes one function, even a simple function should be implemented by writing a method.
Explanation: Although it seems unnecessary to compile methods for functions that can be completed with only one or two lines, using methods can clarify functions, increase program readability, and facilitate maintenance and testing.
7.1.2. It should be clearly stipulated whether the legality check of interface method parameters should be the responsibility of the caller of the method or the interface method itself. The default is the responsibility of the method caller.
Explanation: For the legality check of the parameters of the inter-module interface method, there are often two extreme phenomena, namely: either the caller and the callee do not check the validity of the parameters, and the result is that the legality check is omitted. A necessary processing process causes potential problems; or both the caller and the callee check the validity of the parameters. Although this situation does not cause problems, redundant codes are generated and efficiency is reduced.
7.1.3. Clarify the function of the class, and realize the design of the class precisely (rather than approximately). A class implements only a set of similar functions.
Explanation: When dividing classes, you should try to separate logic processing, data and display to achieve the singleness of class functions.
Example:
Data classes cannot contain logic for data processing.
Communication classes cannot contain logic for explicit processing.
7.1.4. All data classes must overload the toString() method to return meaningful content of the class.
Explanation: If the parent class implements a reasonable toString(), the subclass can inherit without rewriting.
Example:
public TopoNode
{
private String nodeName;
public String toString()
{
return "NodeName : " + nodeName;
}
}
7.1.5. Database operations, IO operations and other objects that need to use close() must be closed() in the finally of try-catch-finally.
Example:
try
{
// ... ...
}
catch(IOException ioe)
{
//... ...
}
finally
{
try
{
out. close();
}
catch (IOException ioe)
{
//... ...
}
}
7.1.6. After the exception is caught, if the exception is not handled, the log or ex.printStackTrace() should be recorded.
Explanation: If there is a special reason, it must be explained with a note.
Example:
try
{
//.......
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
7.1.7. The exception thrown by oneself must fill in the detailed description information.
Description: Easy to locate the problem.
Example:
throw new IOException("Writing data error! Data: " + data.toString());
7.1.8. Runtime exceptions are represented by subclasses of RuntimeException, and there is no need to add throws clauses to method declarations that may throw exceptions. Non-runtime exceptions are inherited from Exception, and a throws clause must be added to the method declaration.
illustrate:
Non-runtime exceptions are exceptions whose throwing conditions are determined by the external operating environment. For example, file operations may fail due to the influence of permissions and disk space. This kind of exception is unavoidable for the program itself, and the caller needs to explicitly consider the exception. How to deal with the method when it occurs, so non-runtime exceptions must be marked with a throws clause. Failure to mark or the caller not catching this type of exception will cause compilation failure, thereby preventing programmers from being negligent.
Runtime exceptions are exceptions caused by poor consideration of the program itself during the running process, such as passing in wrong parameters. The purpose of throwing a runtime exception is to prevent the exception from spreading, which makes it difficult to locate. Therefore, when designing the exception system, it is necessary to reasonably choose the inheritance relationship of custom exceptions according to the nature of the error.
There is also an exception inherited from Error, which is maintained by the virtual machine itself, indicating that a fatal error has occurred and the program cannot continue to run, such as insufficient memory. Our own programs should not catch this exception, nor should they create this type of exception.
7.1.9. Whether to use exception handling or error return code handling in the program depends on whether it is beneficial to the program structure, and exceptions and error codes should not be mixed. It is recommended to use exceptions.
illustrate:
A system or module should uniformly plan the meaning of exception types and return codes.
However, exceptions cannot be used for general process processing. Do not use exceptions too much. The processing efficiency of exceptions is lower than that of conditional branches, and the jump process of exceptions is difficult to predict.
7.1.10. *Pay attention to the precedence of operators, and use parentheses to clarify the order of operations of expressions, avoiding the use of default precedence.
Description: Prevent misunderstandings when reading the program, and prevent program errors due to the inconsistency between the default priority and the design idea.
Example:
expressions in the following statements
word = (high << 8) | low (1)
if ((a | b) && (a & c)) (2)
if ((a | b) < (c & d)) (3)
if written as
high << 8 | low
a | b && a & c
a | b < c & d
(1) (2) Although there is no error, the statement is not easy to understand; (3) The judgment condition is wrong.
7.1.11. *Avoid using numbers that are difficult to understand, and replace them with meaningful symbols. Constants that involve physical states or contain physical meanings should not be directly used as numbers, but must be replaced by meaningful static variables.
Example: The following program is poorly readable.
if (state == 0)
{
state = 1;
... // program code
}
Should be changed to the following form:
private final static int TRUNK_IDLE = 0;
private final static int TRUNK_BUSY = 1;
private final static int TRUNK_UNKNOWN = -1;
if (state == TRUNK_IDLE)
{
state = TRUNK_BUSY;
... // program code
}
7.1.12. Use int[] index instead of int index[] when declaring an array.
Explanation: Using the int index[] format makes the program less readable
Example:
The following program is less readable:
public int getIndex()[]
{
....
}
The following program is more readable:
public int[] getIndex()
{
....
}
7.1.13. When debugging code, do not use System.out and System.err for printing, but use a test class that contains a unified switch for unified printing.
Note: When the code is released, the debugging code can be turned off uniformly, and the switch can be turned on when the problem is located.
7.1.14. Use the debugging switch to switch between the DEBUG version and the official version of the software, instead of having different source files of the official version and the DEBUG version at the same time, so as to reduce the difficulty of maintenance.
7.2. Recommendations
7.2.1. Record exceptions Do not save exception.getMessage(), but record exception.toString().
Example:
When NullPointException is thrown, it is often described as null, so it is often not obvious what is wrong.
7.2.2. A method should not throw too many types of exceptions.
Note: If classification processing is required in the program, organize exceptions into inheritance relationships according to classification. If there are indeed many exception types, first consider using exception descriptions to distinguish them. It is best not to exceed three exceptions marked by the throws/exception clause.
7.2.3. Try not to directly catch (Exception ex) when catching exceptions, and should handle exceptions subdivided.
7.2.4. *If multiple pieces of code do the same thing repeatedly, there may be problems in the division of methods.
Explanation: If there is a substantial relationship between the statements of this code and they complete the same function, then consider constructing this code as a new method.
7.2.5. For the main class created, it is best to put the main() function, containing the code for testing that class.
Description: The main classes include:
- Classes that can complete independent functions, such as communication.
- A class with a complete interface, such as a dialog box, a window, a frame, etc.
- The JavaBean class.
Example:
public static void main(String[] arguments)
{
CreateCircuitDialog circuitDialog1 = new CreateCircuitDialog (null,
"Ciruit", false);
circuitDialog1.setVisible(true);
}
7.2.6. If the data in the collection is not used, it should be released in time, especially for reusable collections.
Explanation: Since the collection saves the handle of the object, the garbage collector of the virtual machine will not recycle.
7.2.7. *The closely related codes in the source program should be as adjacent as possible.
Description: It is convenient for the program to read and find.
Example: The length and width of a rectangle are closely related and put together.
rect.length = 10;
rect. width = 5;
7.2.8. *Do not use difficult and highly technical statements unless it is necessary.
Explanation: High-tech statements are not equal to high-efficiency programs. In fact, the key to program efficiency lies in algorithms.
8. JTEST specification
8.1. Rules
- Every case statement in switch should contain break or return.
- Do not use empty for, if, while statements.
- Do not reduce the precision of the data in the operation.
- The case keyword in the switch statement should keep a space with the following constant, and useless labels other than case should not be defined in the switch statement.
- Do not use the equal sign = in the if statement for assignment.
- Static members or methods are accessed using class names, not handles.
- When the method is overloaded, be sure to pay attention to the same method name to avoid using two very similar method names in the class.
- Do not call the serResize() method in the ComponentListener.componentResized() method.
- Do not override static and private methods of the parent class.
- Do not override the properties of the parent class.
- Do not use more than two levels of inner classes.
- Define the inner class as a private class.
- Remove redundant definitions in the interface (do not use public, abstract, static, final, etc., which are the default in the interface).
- Do not define local variables, class private attributes, class private methods, and method parameters that will not be used.
- Explicitly initialize all static properties.
- Do not use the System.getenv() method.
- Do not hardcode '\n' and '\r' as newline symbols.
- Do not use interfaces in java.awt.peer.* directly.
- Use System.arraycopy() to copy arrays without loops.
- Avoid unnecessary instanceof comparison operations and class modeling operations.
- Do not remove listeners in the finalize() method.
- Be sure to call the super.finalize() method in the finalize() method.
- Call the super.finalize() method in finally in the finalize() method.
- When performing character conversion, there should be as few temporary variables as possible.
- After using the method of ObjectStream, call reset() to release the object.
- In thread synchronization, use conditional tests in loops (use while(isWait) wait() instead of if(isWait) wait()).
- Do not use the resume(), suspend(), stop() methods of the Thread class.
- To reduce the complexity of a single method, use less than 10 if, while, for, and switch statements.
- In Servlets, reuse the data source of the JDBC connection.
- Reduce the number of synchronization methods used in Servlets.
- Do not define friendly properties, methods, and classes that are not used in the package.
- Friendly classes without subclasses should be defined as final.
- Friendly methods that are not covered should be defined as final.
8.2. Recommendations
- Provide a default option to the switch statement.
- Don't assign a value to the counter in the body of the for loop.
- Do not define public builders for non-public classes.
- Do not perform comparison operations on floating-point numbers, especially do not perform ==, != operations, and reduce >, < operations.
- When implementing the equals() method, first use getClass() or instanceof for type comparison, and then continue the comparison after passing.
- Do not overload the main() method for purposes other than entry.
- The parameter name of the method should not be the same as the method name in the class.
- Except for constructors, do not use method names that are the same as class names.
- Instead of defining subclasses of Error and RuntimeException, subclasses of Exception can be defined.
- The run() method needs to be implemented in the thread.
- Use equals() to compare whether the values of two classes are the same.
- When concatenating a character string with the result of a numerical operation, the part of the numerical operation should be enclosed in parentheses.
- Do not use non-private (public, protected and friendly) non-static properties in the class.
- In a class, for an interface that is not implemented, it should be defined as an abstract method, and the class should be defined as an abstract class. (Level 5)
- Do not explicitly import java.lang.* packages;
- Do not use non-static properties of the class when initializing.
- Explicitly initialize all local variables.
- Arrange the methods according to the method name, and the methods of the contract type with the same name should be put together.
- Do not use nested assignments, that is, use multiple = in an expression.
- Do not call abstract methods in the constructor of abstract classes.
- While overloading the equals() method, the hashCode() method should also be overloaded.
- The utility class (Utility) does not define builders, including private builders.
- Do not use more than 10 case statements in a switch.
- Put the main() method at the end of the class.
- Do not use Exception when declaring method violations, use its subclasses.
- Don't throw an Error directly, you should throw its subclass.
- When making comparisons, always put constants on the same side (both on the left or both on the right).
- Whenever possible, always define a default constructor for a class.
- When catching exceptions, do not use Exception, RuntimeException, Throwable, and use their subclasses as much as possible.
- Define constants in interfaces or tool classes. (Level 5)
- Use capital 'L' for long constants. (Level 5)
- The main() method must be public static void main(String[]). (Level 5)
- Use is at the beginning of the method whose return type is boolean, and other types cannot be used.
- For non-boolean type value methods (getters), start with get, and other types cannot be used.
- For the method of setting the value (setter), start with set, and other types cannot be used.
- The method requires the annotation @param with the same number of parameters.
- Do not use unsupported tags in comments, such as: @unsupported.
- Do not use the Runtime.exec() method.
- Do not customize native methods.
- Use as concise arithmetic symbols as possible.
- Set the initial capacity when using collections.
- The comparison of a single first character uses charAt() instead of startsWith().
- Use the shift operators >>, << for the dividend or the multiplication of the multiplicand to the nth power of 2.
- Use ' ' instead of " " for a character connection, such as: String a = b + 'c'.
- Do not call synchronous methods and use try-catch blocks in the loop body.
- Do not use unnecessary boolean comparisons, such as: if (a.equals(b)), instead of if (a.equals(b)==true).
- Use String for constant strings, and StringBuffer for non-constant strings.
- Don't use complex expressions when judging loop conditions.
- Use the conditional operator "if (condition)?do1:do2;" for the "if (condition) do1; else do2;" statement.
- Do not define variables in the body of the loop.
- Set the initial capacity when using StringBuffer.
- Use local variables for calculations as much as possible.
- Use the '!' operator as little as possible. (Level 5)
- Perform instanceof operations on interfaces as much as possible. (Level 5)
- Do not use Date[] but use long[] instead.
- Do not call finalize() explicitly.
- Do not use static collections, their memory footprint grows without bounds.
- Do not repeatedly call a method to get an object, use local variables to reuse objects.
- In thread synchronization, use notifyAll() instead of notify().
- Avoid deadlocks caused by calling another synchronized method in a synchronized method.
- The wait() and notify() methods cannot be called in an asynchronous method.
- Use wait(), notify() instead of while(), sleep().
- Don't use synchronized methods, use synchronized blocks. (Level 5)
- Define all public methods as synchronized methods. (Level 5)
- The implemented Runnable.run() method must be a synchronous method. (Level 5)
- A class with only abstract methods and final static attributes should be defined as an interface.
- You should and must use super.clone() instead of new in the clone() method.
- Constants must be defined as final.
- Provide termination conditions in for loops.
- Use increment count in for, while loop.
- Use StringTokenizer instead of indexOf() and substring().
- Do not use non-final methods in builders.
- Do not assign values to parameters. (Level 5)
- Do not compare the class of two objects by name, use getClass() instead.
- Security: Try not to use inner classes.
- Security: Try not to make classes cloneable.
- Security: Try not to make interfaces serializable.
- Security: Try not to use friendly methods, properties, and classes.
- Servlet: Do not use java.beans.Beans.instantiate() method.
- Servlet: When HttpSession is no longer used, it should be released as soon as possible using the invalidate() method.
- Servlet: When JDBC resources are no longer used, they should be released as soon as possible using the close() method.
- Servlet: Do not use Servlet's SingleThreadModel, it will consume a lot of resources.
- Internationalization: Don't use a character for logical operations, use Characater.
- Internationalization: Do not perform string concatenation, use MessageFormat.
- Internationalization: Do not use Date.toString() , Time.toString() methods.
- Internationalization: Character and string constants should be placed in resource files.
- Internationalization: Do not use the toString() method for numbers.
- Internationalization: Do not use StringBuffer, StringTokenizer classes.
- Internationalization: Do not use the compareTo(), equals() methods of the String class.
- Complexity: Recommended maximum size:
- Inheritance hierarchy 5 layers
- The number of lines of the class 1000 lines(contains {})
- 10 attributes of the class
- 20 methods of the class
- Class friendly methods 10
- Class private methods 15
- 10 class protection methods
- Class public methods 10
- 20 class call methods
- 5 method parameters
- return statement 1
- The number of method lines is 30 lines
- Method code 20 lines
- Comment rate 30%~50%