A good Code Java code is inseparable from a good architectural design and a set of mature code specifications. This article will share some records on the code specifications of my department.

Code specification

1. Java annotations

It is recommended that all public and interface functions be annotated with canonical Java Doc comments such as:

    /** * queryDataList@paramId Primary key ID *@returnData list@throws ServiceException
     */
    List<Data> queryDataList(String id)throws ServiceException;
Copy the code

This can be used to configure template progression in IDEA: available

<pre> <p> <br>
Copy the code

Wait for the tag to format the Java Doc, otherwise the FMT will be crowded all at once. If it is an HTTP data pull interface, you can even put the request parameters, returns, examples, and interface documentation in a Java Doc for yourself and others to read and understand.

2. Function length

The length of a function is not recommended to exceed 100 lines. When it does, you need to consider whether some steps are reasonable and can be further abstracted into private functions to shorten the length of the function. Each line of code should not exceed 100 characters, which can be configured in idea.

3. Function parameters

In code design, function parameters should not be too many, generally not more than 5, if more than, consider whether to encapsulate part of the data into an object, which will improve the readability

Cyclomatic complexity

What code is cyclomatic complexity, is your code logic of all branches of logic and a formula to compute the code cyclomatic complexity is unfavorable and exorbitant, such as the code a lot of the if and the swicth statements, this time to consider whether can use a static constants a list or a map with a for loop to reduce the cyclomatic complexity of the code, It is generally required that the code for a function be no more than 10 cyclomatic complexity (this layer, no recursion), and anything more than 10 is generally confusing.

Unit testing

We require that all code, except the configuration class code, have corresponding unit test code. Good unit testing can avoid 90 percent of bugs, which I share in another article juejin.cn/post/696391…

6. Versioning poM file parameters

Our group requires that all maven dependencies be versially parameterized. I personally feel that it is ok to parameterize some packages common to projects and subprojects, such as Shiro, mysql, Spring, HTTP, etc. The advantage of this is that the packages of the unified classes facilitate uniform versioning, and there are no dark holes caused by inconsistent versions of packages like Spring-MVC and Spring AOP. Such as:

    <properties>
        <springboot.version>2.1.1. RELEASE</springboot.version>
    </properties>

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${springboot.version}</version>
            <exclusions>
            </exclusions>
        </dependency>
   </dependencies>
Copy the code

7. Constant

For constants, common constants are static string or int parameters. If they change frequently, you are advised to use a configuration file. For constants that do not change often and have detailed business semantics, enumeration classes can be drawn and corresponding messages will be appropriate, making the code much more readable. Both static constants and enumerated classes should be annotated accordingly. Such as:

/** * calculate the data state, applied to XXX display */
public enum DataStatus {

    NO_CONFIG(-1."Not configured"),
    FAIL(0."Calculation failed"),
    COMPLETE(1."Calculation done"),
    EXEMPTION(2."Immunity"),
    NO_INVOLVE(3."Not involved");

    private int status;
    private String des;

    DataStatus(int status, String des) {
        this.status = status;
        this.des = des; }}Copy the code

8. Exception handling

For exception handling, the advice is for general exception, defined as a Runtime exception, a unified by the top capture (you can also use the framework of exception handling, exception handling or using AOP), so need not declared abnormal layers (but the best presentation to throw out the RE anomalies in the Java doc, convenient caller do processing). Special exceptions of a single interface need to be declared. Each layer should have the exception log and processing logic of the layer (even if it is directly thrown up, it needs to process and log). It is recommended not to be careless when typing logs, including the interface that failed, request parameters, and exception stack. For the upper-layer external interface, exception handling should be provided to prevent the service from being directly unavailable due to exception leakage. Internal error exception types and error codes should be defined internally, and corresponding service exception codes should be defined externally for the caller to process.

9. Log specification

On our team, the DEBUG level is used to print auxiliary information for details, INFO is used to print an overall narrative into a component or method, WARN is used to print exceptions that do not crash the entire program, and ERROR is used to print information that may affect the basic components of the entire service or cause fatal errors. For the local or test environment, you can print debug or INFO information. After the adjustment, you are advised to print WARN logs and necessary INFO logs. The more logs, the better. If the interface is complex, it may affect your judgment on problem location. The more critical logs, the more detailed logs are.