Remember a summary of Alibaba code quality inspection problems

Some time ago, we did a code specification quality check for the company’s old project. The Alibaba code check plugin was used to check. The check result was not satisfactory. The old project is heavy and there are more development iteration staff. This article is about these checkpoints. Record it for later review.

The Alibaba code detection plug-in was developed in 2017. Both IDEA and Android Studio can be installed and used and are well received by developers. androidstudio can directly search for plug-ins Alibaba Java Coding Guidelinesfor installation and use.

Blocker

  1. The if and for statements must be in the form of closures, and writing without parentheses is not allowed.

  2. When using regular expressions, make good use of its pre-compilation function, which can effectively speed up compilation.

    Note: Do not define in the method body: Pattern pattern = Pattern.compile (rule);

    public class XxxClass {
          
          
            // Use precompile
            private static Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");
            public Pattern getNumberPattern() {
          
          
                // Avoid use Pattern.compile in method body.
                Pattern localPattern = Pattern.compile("[0-9]+");
                return localPattern;
            }
        }
    
  3. Thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. This processing method allows students to write more clearly the running rules of the thread pool and avoid the risk of resource exhaustion.

    Description: The disadvantages of the thread pool object returned by Executors are as follows:

    a. FixedThreadPool和SingleThreadPool:
    允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。
    b. CachedThreadPool:
    允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。
    

    Personal development suggestion, encapsulate a ThreadPoolExecutor thread pool tool class globally, and manage thread pool applications uniformly.

Critical

  1. When the key of Map/Set is a custom object, hashCode and equals must be rewritten.

    Regarding the processing of hashCode and equals, follow the following rules:

    a. 只要重写equals,就必须重写hashCode。
    b. 因为Set存储的是不重复的对象,依据hashCode和equals进行判断,所以Set存储的对象必须重写这两个方法。 
    c. 如果自定义对象做为Map的键,那么必须重写hashCode和equals。
    
  2. Object's equals method is easy to throw a null pointer exception, you should use constants or objects with certain values ​​to call equals.

  3. You cannot use outdated classes or methods.

  4. When creating a thread or thread pool, please specify a meaningful thread name to facilitate backtracking in case of errors. When creating a thread pool, please use the constructor with ThreadFactory, and provide a custom ThreadFactory implementation or use a third-party implementation.

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
        .setNameFormat("demo-pool-%d").build();
    ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    
    singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
    singleThreadPool.shutdown();
    
        
            
    public class TimerTaskThread extends Thread {
          
          
        public TimerTaskThread(){
          
          
        super.setName("TimerTaskThread");}
    

    Personal development suggestion, encapsulate a ThreadPoolExecutor thread pool tool class globally, and expose the definition of the initial thread name.

  5. In a switch block, each case is either terminated by break/return, etc., or a 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 There is no code.

  6. Constant names should be all capitalized, separated by underscores between words, and strive for complete and clear semantic expression, and don't take long names.

  7. Exception class names end with Exception.

  8. All enumeration type fields must have a comment, explaining the purpose of each data item.

  9. All programming-related names cannot be named under underscores or dollar signs.

  10. Abstract class names start with Abstract or Base, abstract classes generally need to be inherited.

  11. Method names, parameter names, member variables, and local variables all use lowerCamelCase uniformly, and must follow the small camel case

  12. To determine the equivalence between floating-point numbers, basic data types cannot be compared with ==, and packaging data types cannot be judged with equals. Floating-point numbers adopt the encoding method of "mantissa + order code", which is similar to the expression method of "significant digit + exponent" in scientific notation. Binary system cannot accurately represent most decimal fractions. For specific principles, please refer to "Code Efficient".
    How to improve:

        1)指定一个误差范围,两个浮点数的差值在此范围之内,则认为是相等的
            float a = 1.0f - 0.9f;
            float b = 0.9f - 0.8f;
            float diff = 1e-6f;
        
            if (Math.abs(a - b) < diff) {
          
          
                System.out.println("true");
            }
        2) 使用BigDecimal来定义值,再进行浮点数的运算操作
            BigDecimal a = new BigDecimal("1.0");
            BigDecimal b = new BigDecimal("0.9");
            BigDecimal c = new BigDecimal("0.8");
        
            BigDecimal x = a.subtract(b);
            BigDecimal y = b.subtract(c);
        
            if (x.equals(y)) {
          
          
                System.out.println("true");
            }
                    
        Negative example:
                float g = 0.7f-0.6f;
                float h = 0.8f-0.7f;
                if (g == h) {
          
          
                    System.out.println("true");
                }
         
         
         
        Positive example:
                double dis = 1e-6;
                double d1 = 0.0000001d;
                double d2 = 0d;
                System.out.println(Math.abs(d1 - d2) < dis);
    
    
  13. Thread resources must be provided through the thread pool, and it is not allowed to explicitly create threads in the application.

    Description: The advantage of using the thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources, and to solve the problem of insufficient resources. If the thread pool is not used, it may cause the system to create a large number of threads of the same type and cause memory consumption or "excessive switching" problems.

Major

  1. No magic value (ie, undefined constant) is allowed to appear directly in the code.
    Negative example:
        //Magic values, except for predefined, are forbidden in coding.
        if (key.equals("Id#taobao_1")) {
          
          
                //...
        }
             
            
            
    Positive example:
        String KEY_PRE = "Id#taobao_1";
        if (KEY_PRE.equals(key)) {
          
          
                //...
        }
    
  2. The brackets are part of the array type, and the array is defined as follows: String[] args
Negative example:
        String extArrayString[] = {
    
     ".amr", ".ogg", ".mp3", ".aac", ".ape",
				".flac", ".wma", ".wav", ".mp2", ".mid", ".3gpp" };
  1. The package name is uniformly lowercase, and there is only one natural semantic English word between the dot separators. Package names use the singular form uniformly, but if the class name has a plural meaning, the class name can use the plural form.

    Personal advice, if you encounter a package name that must be expressed in two or more words, you can use Spring's naming method, and the two words are separated by dots; during the development process, we try to use one word to express.

  2. The total number of lines in a single method does not exceed 80 lines.

    Note: The total number of lines except for the method signature, closing curly brace, method code, blank line, carriage return, and any invisible characters does not exceed 80 lines.

  3. Clean up code segments or configuration information that are no longer used in time.

    Note: For junk code or outdated configuration, resolutely clean up to avoid excessive program bloat and code redundancy.

  4. In the loop body, the connection method of strings is extended using the append method of StringBuilder.

    Note: The decompiled bytecode file shows that a StringBuilder object will be newly generated in each loop, and then append operation is performed, and finally the String object is returned through the toString method, causing a waste of memory resources.

    Negative example:
            String result;
            for (String string : tagNameList) {
          
          
                result = result + string;
            }
    
        
            
    Positive example:
            StringBuilder stringBuilder = new StringBuilder();
            for (String string : tagNameList) {
          
          
                stringBuilder.append(string);
            }
            String result = stringBuilder.toString();
    
  5. All abstract methods (including methods in interfaces) must be annotated with javadoc. In addition to return values, parameters, and exception descriptions, they must also indicate what the method does and what functions it implements.

    Note: If there are implementation and call precautions, please explain them together.

  6. Single-line comment inside the method, start a new line above the commented statement, use // comment. Use /* */comment for multi-line comments inside the method. Pay attention to alignment with the code.

        public void method() {
          
          
            // Put single line comment above code. (Note: align '//' comment with code)
            int a = 3;
        
            /**
            * Some description about follow code. (Note: align '/**' comment with code)
            */
            int b = 4;
        }
    
  7. The annotations of classes, class attributes, and class methods must use javadoc specifications, use /* content /format, and must not use //xxx method and / xxx / method. Note: In the IDE editing window, the javadoc method will prompt the relevant comments, and the generated javadoc can correctly output the corresponding comments; in the IDE, when the project calls the method, the meaning of the prompt method, parameter, and return value can be suspended without entering the method to improve reading effectiveness.

        /**
         * 
         * XXX class function description.
         *
         */
        public class XxClass implements Serializable {
          
          
            private static final long serialVersionUID = 113323427779853001L;
            /**
             * id
             */
            private Long id;
            /**
             * title
             */
            private String title;
        
            /**
             * find by id
             * 
             * @param ruleId rule id
             * @param page start from 1
             * @return Result<Xxxx>
             */
            public Result<Xxxx> funcA(Long ruleId, Integer page) {
          
          
                return null;
            }
        }
    
  8. The class name uses the UpperCamelCase style and must follow the camel case form, except for the following cases: (Related naming of the domain model) DO / BO / DTO / VO / DAO

  9. Except for common methods (such as getXxx/isXxx), etc., do not execute complex statements in conditional judgments, and assign the result of complex logical judgments to a meaningful Boolean variable to improve readability.

    Explanation: The logic in many if statements is quite complicated. The reader needs to analyze the final result of the conditional expression to know what kind of condition to execute what kind of statement. Then, what if the reader analyzes the logical expression wrong?

    
    Negative example:
            if ((file.open(fileName, "w") != null) && (...) || (...)) {
          
          
                // ...
            }
    		
    		
    		
    Positive example:
            boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
            if (existed) {
          
          
                //...
            }
    
  10. When the collection is initialized, specify the initial value of the collection.

    Note: HashMap uses the following construction method to initialize. If the collection size cannot be determined temporarily, then specify the default value (16).

     Negative example:   
       Map<String, String> map = new HashMap<String, String>();
        
        
        
     Positive example: 
       Map<String, String> map = new HashMap<String, String>(16);
    

Guess you like

Origin blog.csdn.net/li0978/article/details/106146477