The number and types of non-standard codes in an internal Java project prepared for open source are counted. The data is sensitive and inconvenient to be disclosed. But the most common types of irregularities can be described.
Earlier, I also shared code specifications and tried to guess which code specification problems might be committed, but the problem could not be solved by guessing. I used the internal project plug-in to scan and counted all code problems as follows.
Code specification issues
named
The most common problem, nearly half the naming problems in the code specification are committed.
1 Package names should be all lowercase
[Mandatory] The package name is all lowercase, and there is only one natural semantic English word between the dot delimiters. The package name is singular, but the class name can be plural. Example: Application utility class package named com.alibaba.ai.util and class named MessageUtils (refer to Spring framework for this rule)
2 The name cannot start with an _ or $
No naming in code can begin or end with an underscore or a dollar sign.
Example: __name / $name
Use the UpperCamelCase style for class 3 names
[Mandatory] Use UpperCamelCase for class names, except DO/BO/DTO/VO/AO /
PO/UID, etc.
Example: MarcoPolo/UserDO/XmlService/TcpUdpDeal/TaPromotion
Counterexample: macroPolo/UserDo/XMLService/TCPUDPDeal/TAPromotion
4 Method names do not use the lowerCamelCase style
[Mandatory] Use the lowerCamelCase style for method names, parameter names, member variables, and local variables. Example: localValue/getHttpMessage()/inputUserId
Constant names should be all uppercase and separated by an underscore
[Mandatory] Constant names are all capitalized, words are separated by underscores, and semantic expression is complete and clear, not too long name.
Positive example: MAX_STOCK_COUNT Negative example: MAX_COUNT
The Abstract class name should start with Abstract or Base
【 Mandatory 】 Abstract class names begin with Abstract or Base. Exception class names end with Exception; The test class
The name starts with the name of the class it is testing and ends with Test.
POJO Boolean variables without the is prefix
[Mandatory] POJO class Boolean variables, do not add is prefix, otherwise part of the framework parsing will cause serialization errors. Counterexample: the attribute defined as the basic data type Boolean isDeleted, and its method is isDeleted(). During reverse lookup, the RPC framework mistakenly thinks that the corresponding attribute name isDeleted. As a result, the attribute cannot be obtained and exceptions are thrown.
Constants defined
1 mana
Force Does not allow any mana value (i.e., undefined constants) to appear directly in the code.
Example:
String key = “Id#taobao_” + tradeId;
cache.put(key, value);
2 Values of type Long, ending with a capital L
[Mandatory] When assigning a value to long or long, use uppercase L after the value, not lowercase L, because lowercase may be confused with 1. Long a = 2l; Is it a number 21, or a Long 2?
Don’t have a class that maintains all constants
[Recommendation] Do not use a constant class to maintain all constants, according to the constant function group, separate maintenance. Description: large and complete constant class, disorderly, the use of search function to locate the modified constant, is not conducive to understanding and maintenance.
Example: Cache-related constants are stored in the CacheConsts class. System configuration constants are placed under the ConfigConsts class.
Call equals using constants or the contents of validation values
【 mandatory 】Object’s equals method is prone to null-pointer exceptions. Call equals using constants or objects that are determined to have values.
Is: “test”. The equals (object);
Example: the object. The equals (” test “);
Java.util. Objects#equals (a utility class introduced in JDK7)
Code format
1 Too many lines of code
[Recommended] The total number of lines in a single method is not more than 80. The number of valid lines of code is about 40
Note: The total number of lines including method signatures, closing braces, code in methods, comments, empty lines, carriage returns, and any invisible characters cannot exceed 80
Line.
Example: Code logic distinguishes red flower from green leaf, personality from commonality. Green leaf logic is a separate extra method to make the trunk code clearer. Generic logic extraction becomes a generic method, which is easy to reuse and maintain.
2 File codes are inconsistent
【 mandatory 】IDE text file encoding is set to UTF-8; Newlines for files in IDE use Unix format, not Windows format.
Set processing
1 When initializing a collection such as HashMap, specify the initial value as much as possible
[Recommendation] Specify the initial value of the collection when the collection is initialized. Note: HashMap is initialized using HashMap(int initialCapacity).
InitialCapacity =(Number of elements to be stored/load factor) + 1. Note that the default load factor (loaderfactor) is 0.75. If you cannot determine the initial value, set it to 16 (the default value).
Counterexample: A HashMap requires 1024 elements. As the initial capacity is not set, the capacity is expanded seven times as the number of elements increases. Resize requires the reconstruction of the hash table, which severely affects the performance.
2 Method of traversing the Map
[Recommended] Use entrySet to traverse the Map class KV instead of keySet.
The keySet is iterated twice, once to an Iterator and once to retrieve the value of the key from the hashMap. EntrySet is more efficient by simply iterating once and putting both keys and values into the entry. For JDK8, use the map.foreach method. Example: Values () returns a set of V values, which is a list object; KeySet () returns a set of K values
A Set collection object; EntrySet () returns a collection of combinations of k-V values.
Control statements
The number of control layers should not be too high
Avoid using if-else when expressing exception branches; this can be overwritten
if (condition) {
.
return obj;
}
If you have to use if()… else if()… else… To avoid subsequent maintenance difficulties, do not exceed three layers.
If-else code with more than 3 layers of logic can have an example of a central guard statement as follows:
public void today() {
if (isBusy()) {
System. The out. Println (” change the time. “);
return;
}
if (isFree()) {
System. The out. Println (” go to travel. “);
return;
}
System.out.println(” Stay at home to learn Alibaba Java Coding Guidelines. “);
return;
}
Do not use complex expressions in conditions
[Recommendation] Do not execute complex statements in conditional judgment except for common methods (such as getXxx/isXxx). Assign the result of complex logical judgment to a meaningful Boolean variable name to improve readability. Note: The logic in many if statements is quite complex, and the reader needs to analyze the final result of the conditional expression to determine what kind of statement to execute. So, what if the reader analyzes the logical expression error? Is:
// The pseudo-code is as follows
final boolean existed = (file.open(fileName, “w”) ! = null) && (…) | | (…). ;
if (existed) {
.
}
Example:
if ((file.open(fileName, “w”) ! = null) && (…) | | (…). ) {
.
}
The 3 if statement is missing braces
Braces must be used in if/else/for/while/do statements. Avoid single statements, even if there is only one line of code: if (condition) statements;
Annotation specifications
1 Use end-of-line comments
[Mandatory] A single line comment inside the method, a new line above the commented statement, using // comment. Method internal multi-line comments using /* */ comments, note alignment with code.
2 The @author information is missing
[Mandatory] All classes must have a creator and creation date added.
@author
@date
3 Use Javadoc comments
[Mandatory] Class, class attribute, class method annotation must use Javadoc specification, use /* content/format, do not use // XXX.
Note: In the IDE editing window, Javadoc mode will prompt the relevant annotations, generated Javadoc can output the corresponding annotations correctly; In IDE, when a project calls a method, the meaning of method, parameter and return value can be suspended without entering the method to improve reading efficiency.
8 Clear unnecessary code segments or configuration information
[Recommendation] Clean up code segments or configurations that are no longer used
Note: For garbage code or outdated configuration, resolutely clean up, avoid excessive bloated procedures, code redundancy.
Example: For code snippets that have been commented out temporarily and may be restored later, it is a uniform rule to use three slashes (///) above the commented code to explain the reason for commenting out the code.
Method arguments are missing Javadoc comments
All abstract methods (including those in the interface) must be annotated in Javadoc, specifying what the method does and implements in addition to return values, parameters, and exception descriptions.
Note: Implementation requirements for subclasses, or call notes, please explain.
5 Enumeration fields are missing comments
[Mandatory] All enumerated type fields must have comments stating the purpose of each data item.
other
1 string concatenation in loop body adopts StringBuilder method
[Recommendation] String concatenation in the loop body, which is extended by using the Append method of StringBuilder. Note: In this example, the decomcompiled bytecode file shows that each time the loop returns a StringBuilder object, the append operation is performed, and the toString method returns a String object, resulting in a waste of memory resources.
Example:
String str = “start”;
for (int i = 0; i < 100; i++) {
str = str + “hello”;
}
2 Create a thread pool
[Mandatory] Thread resources must be provided through a thread pool. Explicit creation of threads in an application is not allowed.
Note: The benefit of using a thread pool is to reduce the time spent creating and destroying threads and the overhead of system resources, solving the problem of insufficient resources. If you do not use thread pools, you can create a large number of similar threads and run out of memory or “overswitch.”
3 The parameter list is too long
[Mandatory] Java variable parameters can be used only when the parameter types and service meanings are the same, instead of Object. Note: Variable arguments must be placed at the end of the argument list. Public List listUsers(String type, Long… ids) {… }
4 Wrap multiple parameters
When multiple arguments in a method call require line breaks, do so after commas.
5 Redirection problem
Internal server redirection uses forward; External redirect addresses are generated using THE URL assembly utility class. Otherwise, inconsistent URL maintenance and potential security risks may occur.
The last
These are some of the most common code mistakes, and what the code specification suggests to do about them.