Summary of common development specifications in Java project practice

Posted by sambo80 on Mon, 03 Jan 2022 14:15:52 +0100


With reference to Alibaba's development manual and in combination with the actual situation, the common development specifications of the project are summarized and continuously updated...

1. Naming

Alibaba's development manual contains detailed naming specifications, which are recommended to be followed.

1.1 it is strictly prohibited to use pinyin (except for international use).

1.2 follow the hump naming.

1.3 constant names are all capitalized and separated by underscores.

1.4 naming type

Abstract classes start with abstract or Base, Exception classes end with Exception, Test classes end with Test, and interfaces end with Impl or I (choose one of IUserService and UserServiceImpl in the whole project).

1.5 abbreviation specification

Positive examples: number > num, document > doc, string > str. Counterexample: AbstractClass > absclass.

1.6 if a design pattern is used, it is recommended to reflect the specific pattern when naming.

1.7 naming protocol of Service/DAO layer method

1) the method of obtaining a single object is prefixed with get. (getUser)

2) the method of obtaining multiple objects ends with list. (getUserList)

3) the method of obtaining statistical value is prefixed with count. (countUser)

4) the insertion method is prefixed with insert. (insertUser)

5) delete method is prefixed with delete. (deleteUser)

6) the modification method is prefixed with update. (updateUser)

1.8 domain model naming protocol

1) data object: xxxDO, xxx is the data table name.

2) data transmission object: xxxDTO, xxx is the name related to the business field.

3) display object: xxxVO, xxx is generally the web page name.

4) business object: xxxBO, xxx are generally class I business names

Additional suggestions: naming should be based on the premise that the meaning can be clearly expressed. The shorter the better. Make rational use of abbreviations. Naming should be readable, searchable and associative as much as possible.

2. Code style

2.1 unified format

public static void main(String[] args) { 
    // Indent 4 spaces 
    String say = "hello"; 
    // There must be a space on the left and right of the operator 
    int flag = 0; 
    // There must be a space between the keyword if and the bracket. The f in the bracket and the left bracket, 0 and the right bracket do not need a space 
    if (flag == 0) { 
    // The left brace is preceded by a space and does not wrap; Wrap after left brace 
    if (flag == 1) { 
    // Wrap before the right brace, else after the right brace, no line wrapping 
    } else { 
    // If it ends directly after the closing brace, it must wrap 

2.2. How big is a class or method?

Generally, according to the complexity of sonar middle circle, it is recommended that the complexity of a method should not exceed 5. Some companies directly look at the number of lines of code. If the code of a method exceeds 50, it is considered that the method needs to be split. Generally, the number of lines that can be displayed on a whole screen of a computer is almost 50, but it can not be generalized. Combined with the actual situation, In order to ensure good code reading.

2.3 length of one line of code

For single line code, it is recommended not to exceed 100 characters, which is also based on the width that can be displayed on a whole screen of the computer. If it exceeds 100 characters, a new line is required.

1) The second line is indented by 4 spaces relative to the first line. Start from the third line and do not continue to indent. Refer to the example.

2) Operator to wrap a line with the following.

3) The dot symbol of the method call wraps with the following line.

4) When calling a method, multiple parameters need to be wrapped after a comma.

5) Do not wrap before parentheses, see counterexample

// Positive example
StringBuffer sb = new StringBuffer();

// Counterexample
StringBuffer sb = new StringBuffer();

// Counterexample
method(args1, args2, args3, ... 
, argsX);

2.4. Number of parameters in a method

It is recommended that the number of parameters of a method should not exceed 5. Too many parameters will affect the readability and maintainability of the code. Considering a single responsibility, it is recommended to split multiple methods to reduce the number of parameters. If the responsibility is single but multiple parameters are still required, it is recommended to seal them as objects.

2.5 shielding details

Too many details in a method will affect the readability and maintainability of the code and shield the details. What isLastDayOfMonth() needs to do is clear at a glance, so as not to let other colleagues looking at the code fall into the specific implementation of too many details.

// Counterexample

// ... Context service
LocalDate today =;
LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
boolean isLastDayOfMonth = Period.between(today, lastDayOfMonth).getDays() == 0;
// ... Context service

// Positive example

// ... Context service
// ... Context service

private static boolean isLastDayOfMonth() {
    LocalDate today =;
    LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
    return Period.between(today, lastDayOfMonth).getDays() == 0;

3. Constant

3.1 magic value

Replace the magic value with a constant. The name of the constant should be interesting. The purpose of solving the existence of magic value is to use explanatory variables. Otherwise, it is playing hooligans.

// Counterexample
public static final int LIMIT = 100;

// Positive example
public static final int ORDER_EXPORT_MAX_LIMIT = 100;

3.2. Do not use large and complete constants

Do not use a constant class to maintain all constants. Classify them according to the constant function and maintain them separately.

Cache constant: CacheConstant, configuration class: ConfigConstant

3.3 constant directory

Constants should not be defined everywhere.

1) Cross application shared constants: defined in the core package.

2) Intra application shared constants: defined in the unified directory, usually in the constant directory in modules.

3) Shared constants within a class: private static final is defined directly within the class.

3.4 enumeration

If the variable value has an extended attribute other than the name, it is defined as an enumeration class.

public Enum {

3.5. Set and array constant definition specification

     * Constant list
    public static final List<Integer> CONST_LIST = Collections.unmodifiableList(Arrays.asList(1, 2, 3));
     * Constant set
    public static final Set<Integer> CONST_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(1, 2, 3)));
     * Constant map
    public static final Map<String, String> CONST_VALUE_MAP;

    static {
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("k1", "v1");
        valueMap.put("k2", "v2");
        valueMap.put("k3", "v3");
        CONST_VALUE_MAP = Collections.unmodifiableMap(valueMap);

4. Unified tool class

The tool classes used in the project are provided uniformly, such as date tool class, collection tool class and numerical calculation tool class.

5. Concurrent correlation

5.1 thread pool

Where threads need to be used, they are all provided through the thread pool. The thread pool should not be created using Executors, but must be created through ThreadPoolExecutor, and a meaningful thread name should be specified.

5.2 affairs

It is forbidden to define @ Transactional directly on the service method. Pay attention to the situations that will lead to transaction failure. In principle, try to narrow the scope of transactions.

5.3 lock

1) One principle is not to use locks if no locks can be used, pessimistic locks if optimistic locks can be used (if the collision probability of each access is less than 20%, it is recommended to use optimistic locks), code blocks that can be locked do not lock the whole method body, and objects that can be locked do not lock classes.

2) Pay attention to the sequence of adding and releasing locks to avoid deadlock.

5.4 thread safety

Value type: AtomicXXX

Date type usage: you can use Instant instead of date, LocalDateTime instead of Calendar, and DateTimeFormatter instead of SimpleDateFormat.

Other common thread safety classes:

StringBuilder (thread unsafe), StringBuffer (thread safe).

Thread safe classes such as Map, Set, List, etc.

6. Notes

1) The main content of the note is suggested to include three aspects: what to do, why and how to do it.

2) Comments should be summative and make the code structure look clearer.

3) TODO marks the to-do, and the processing time needs to be confirmed

4) FIXME tag error, processing time needs to be confirmed

Topics: Java