Java development manual and specification

In order to facilitate project maintenance and standard development and promote the efficiency of Code Review among members, the following development specifications are proposed
According to the binding force, the regulations are divided into three categories: mandatory, recommended and reference:

[mandatory] must be observed, and violation of this Agreement may cause serious consequences;

[recommendation] try to comply. Long term compliance will help improve system stability and cooperation efficiency;

[reference] fully understand that the guidance of technical awareness is the direction of individual learning, team communication and project cooperation.

1, Naming conventions
1. The naming in the [mandatory] code cannot start or end with an underscore or dollar sign.

// Examples of errors: 
name / name / $name / name / name$ / name

2. [mandatory] it is forbidden to use the method of mixing Pinyin and English for naming in the code, and it is not allowed to use Chinese directly (even pure Pinyin naming method should be avoided).

// Correct example:
alibaba / taobao / youku / hangzhou And other international names can be regarded as English.

// Examples of errors:
int A variable = 3

3. [force] the class name to use UpperCamelCase style.

// Correct example:
MarcoPolo / UserDO / XmlService

// Examples of errors:
macroPolo / UserDo / XMLService

4. [mandatory] method name, parameter name, member variable and local variable all use lowerCamelCase style, and must follow hump form.

// Correct example:
localValue / getHttpMessage() / inputUserId

5. [mandatory] all constant names are capitalized, and words are separated by underscores, so as to strive for complete and clear semantic expression, and do not be too long.

// Correct example:

// Examples of errors:

6. The [mandatory] type is next to the brackets to define the array.

// Correct example: 
int[] arrayDemo

// Examples of errors: 
String args[]

7. [recommended] in order to achieve the goal of code self interpretation, any user-defined programming element shall be named with as complete word combinations as possible to express its meaning. Eliminate completely nonstandard abbreviations.

//Correct example: 
Class named PullCodeFromRemoteRepository

// Examples of errors:
Variable: int a;
AbstractClass"The abbreviation "is named AbsClass´╝Ť

8. [reference] enumerating class names are recommended to be suffixed with Enum. Enumerating member names should be capitalized and separated by underscores.

// Correct example:
// Enumeration type: 
// Members: 

2, Constant definition
1. [mandatory] no magic value (i.e. undefined constant) is allowed to appear directly in the code.

// Examples of errors: 
String key = "Id#taobao_" + x;

2. [mandatory] when long or long is initially assigned, use upper case l instead of lower case L. lower case is easy to be confused with number 1, resulting in misunderstanding.

// Correct example:
Long a = 2L;

// Examples of errors:
Long a = 2l;

3. [recommended] if the variable value changes only within a fixed range, it is defined by enum type.

3, Code format
1. [mandatory] if the braces are empty, simply write it as {}, and there is no need for line breaks and spaces in the middle of the braces; If it is a non empty code block, there is no line break before the left brace; Wrap after left brace; Wrap before closing brace; If there are else and other codes after the right brace, there is no line break; A closing brace indicating termination must be followed by a newline.

2. [mandatory] there is no space between the left parenthesis and the adjacent characters on the right; There is no space between the right parenthesis and the adjacent characters on the left; The left brace needs to be preceded by a space.

3. [mandatory] spaces must be added between reserved words such as if/for/while/switch/do and brackets.

// Correct example:
if (a == b) {
	method(args1, args2, args3);
} else if (a > b) {
	method(args1, args2, args3);
} else {}

4. [mandatory] a space should be added on the left and right sides of any binomial or ternary operator.

// Correct example: 
int y = 0;
int b = 1;
int x = (y > b) ? b : y;

5. [mandatory] there is only one space between the double slash of the note and the content of the note.

// Correct example:
// This is an example comment, notice that there is a space after the double slash

6. [coercion] during type coercion, there is no need to separate any space between the right bracket and the cast value.

// Correct example:
double first = 3.2d;
int second = (int)first + 2;

7. When defining and passing in [mandatory] method parameters, multiple parameter commas must be followed by spaces.

// Correct example:
method(args1, args2, args3);

8. [recommended] insert a blank line between codes with different logic, semantics and businesses to improve readability.

4, Collection processing
1. [force] judge whether the elements in all sets are empty, and use isEmpty() method instead of size()==0.

// Correct example:
Map<String, Object> map = new HashMap<>(16);
if(map.isEmpty()) {
	System.out.println("no element in this map.");

2. [mandatory] the subList result of ArrayList cannot be forcibly converted to ArrayList, otherwise ClassCastException will be thrown.

3. [force] when using the method keySet()/values()/entrySet() of Map to return a collection object, you can't add elements to it, otherwise an unsupported operationexception will be thrown.

4. [forced] the objects returned by the Collections class, such as emptyList()/singletonList(), are immutable list s, and cannot be added or deleted.

5. [force] to use the method of converting a set to an array, you must use the toArray(T[] array) of the set. The passed in is an empty array with exactly the same type and length of 0.

// Correct example:
List<String> list = new ArrayList<>(2);
String[] array = list.toArray(new String[0]);

6. [mandatory] when a set without generic restriction definition is assigned to a set with generic restriction, instanceof judgment is required when using set elements to avoid throwing ClassCastException exceptions.

// Correct example:
List<String> generics = null;
List notGenerics = new ArrayList(10);
notGenerics.add(new Object());
notGenerics.add(new Integer(1));
generics = notGenerics;

// Examples of errors:
String string = generics.get(0);

7. [mandatory] do not remove/add elements in the foreach loop. For the remove element, please use the Iterator method. If concurrent operations occur, you need to lock the Iterator object.

// Correct example:
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
	String item =;
	if (Conditions for deleting elements) {

// Examples of errors:
for (String item : list) {
	if ("1".equals(item)) {

8. [recommended] when initializing a set, specify the initial value size of the set.

9. [recommended] use entrySet instead of keySet to traverse the Map class set KV.

10. [reference] using the unique feature of the Set element, you can quickly de duplicate a Set to avoid traversing and de duplication or judging inclusion using the contents() of the List.

5, Concurrent processing
1. [forced] when creating a thread or thread pool, please specify a meaningful thread name to facilitate backtracking in case of error.

2. [mandatory] thread resources must be provided through the thread pool. It is not allowed to create threads explicitly in the application.

3. [mandatory] thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. This processing method makes the writing students more clear about the operation rules of thread pools and avoid the risk of resource depletion.

4. [mandatory] SimpleDateFormat is a thread unsafe class. Generally, it should not be defined as a static variable. If it is defined as static, it must be locked, or use the DateUtils tool class.

Correct example:
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
	protected DateFormat initialValue() {
		return new SimpleDateFormat("yyyy-MM-dd");

5. [forced] in case of high concurrency, the performance loss of lock should be considered in synchronous call. If you can use a lock free data structure, do not use a lock; If you can lock blocks, don't lock the whole method body; If you can use object locks, don't use class locks.

6. [force] in the way of using the attempt mechanism to obtain the lock, you must first judge whether the current thread holds the lock before entering the business code block. The release rule of lock is the same as the blocking waiting mode of lock.

// Correct example:
Lock lock = new XxxLock();
boolean isLocked = lock.tryLock();
if (isLocked) {
	try {
	} finally {

7. [forced] when multithreading processes scheduled tasks in parallel, when Timer runs multiple timetasks, as long as one of them does not catch the thrown exception, the other tasks will automatically terminate. Using ScheduledExecutorService does not have this problem.

6, Control statement
1. [mandatory] in a switch block, each case is either terminated through continue/break/return, or the comment indicates which case the program will continue to execute; In a switch block, a default statement must be included and placed at the end, even if it has no code.

2. [mandatory] when the variable type in switch brackets is String and this variable is an external parameter, null judgment must be performed first.

// Examples of errors:
public class SwitchString {
	public static void main(String[] args) {

	public static void method(String param) {
		switch (param) {
			// Definitely not here
			case "sth":
				System.out.println("it's sth");
			// Not here
			case "null":
				System.out.println("it's null");
			// Not here

3. [mandatory] braces must be used in if/else/for/while/do statements. Even if there is only one line of code, encoding without braces is prohibited: if (condition) statements.

4. [mandatory] ternary operator condition? Expression 1: in expression 2, it is highly noted that NPE exceptions caused by automatic unpacking may be thrown when types of expressions 1 and 2 are aligned.

// Examples of errors:
Integer a = 1;
Integer b = 2;
Integer c = null;
Boolean flag = false;
// If the result of a*b is int type, c will force unpacking into int type and throw NPE exception
Integer result=(flag ? a*b : c); 

5. [recommended] when expressing abnormal branches, use less if else. If you don't use if()... else if()... Else... To express logic, avoid the difficulty of subsequent code maintenance, and don't exceed 3 layers.

// Correct example:
public void findBoyfriend (Man man) {
	if (man.isUgly()) {
		System.out.println("This girl is a senior member of the appearance Association");
	if (man.isPoor()) {
		System.out.println("To a destitute couple nothing goes well.");
	if (man.isBadTemper()) {
		System.out.println("As far as the Milky way is, roll away");
	System.out.println("You can go out for a while");

6. [recommended] except for common methods (such as getXxx/isXxx), do not execute other complex statements in condition judgment, and assign the result of complex logic judgment to a meaningful boolean variable name to improve readability.

7. [recommended] do not insert assignment statements into other expressions (especially conditional expressions).

8. [recommended] avoid using negative logical operators.

7, Notes
1. [mandatory] the annotation of class, class attribute and class method must use Javadoc specification, use / * content / format, and cannot use / / xxx.

2. [mandatory] all abstract methods (including methods in the interface) must be annotated with Javadoc. In addition to the return value, parameters and exception description, it must also indicate what the method does and what functions it implements.

3. [mandatory] all classes must add creator and creation date.

4. The [force] method has a single line comment inside. Start another line above the annotated statement and use / / to comment. The / * * / annotation is used for the multi line annotation inside the method. Pay attention to the alignment with the code.

5. [mandatory] all enumeration type fields must be annotated to explain the purpose of each data item.

6. [recommended] while modifying the code, the comments should also be modified accordingly, especially the parameters, return values, exceptions, core logic, etc.

7. [recommended] delete any unused fields, methods and internal classes in the class; Delete any parameter declarations and internal variables that are not used in the method.

Reference document (ALI java development manual): Java Development Manual (Songshan version). pdf

Open source project path:

Tags: Java Back-end

Posted on Wed, 03 Nov 2021 00:16:08 -0400 by kustomjs