Programming Statute (refer to Ali Baba Java Development Manual)

1. Name style

  • Enforcement
    • Code name can not start with an underscore or a dollar sign, can not end with an underscore, or dollar sign.
      • 反例:_name / __name / $name / name_ / name$ / name__
    • Code named prohibited use Pinyin mixed with English, but does not allow direct use of Chinese fashion.
      • Description: correct English spelling and grammar allows readers easy to understand, avoid ambiguity. Note that the naming of pure phonetic but also to be avoided.
      • Positive examples: renminbi / alibaba / taobao / youku / hangzhou international generic name, visual with English.
      • Anti Example: DaZhePromotion [discount] / getPingfenByName () [Review] / int variable a = 3
    • UpperCamelCase style using the class name, but the following exceptional circumstances: DO / BO / DTO / VO / AO / PO / UID like.
      • 正例:JavaServerlessPlatform / UserDO / XmlService / TcpUdpDeal / TaPromotion
      • 反例:javaserverlessplatform / UserDo / XMLService / TCPUDPDeal / TAPromotion
    • Method name, parameter name, member variables, local variables are consistent use lowerCamelCase style, you must comply with the hump form.
      • 正 例: localValue / getHttpMessage () / inputUserId
    • Constant naming all uppercase, separated by an underscore between words, semantic integrity and strive to clear, not too long name.
      • 正例:MAX_STOCK_COUNT / CACHE_EXPIRED_TIME
      • 反例:MAX_COUNT / EXPIRED_TIME
    • Abstract class name or the beginning of the use Abstract Base; exception class named using ends Exception; test class named after the name of its class to be tested beginning to the end of the Test.
    • Type brackets represent immediately connected to the array.
      • Example n: integer array defined int [] arrayDemo;
      • Anti Example: In the main parameter, a String args [] is defined.
    • POJO class Boolean variables do not add the prefix is ​​otherwise resolved portion of the frame can cause serialization error.
      • Description: MySQL build the table agreed in the statute, the expression value or not is employed is_xxx naming, therefore, necessary to <resultMap> mapping from is_xxx provided to the xxx.
      • Anti Example: is defined as the basic data types Boolean isDeleted property that the method is also isDeleted (), RPC frame when the reverse analysis, "mistake" is deleted corresponding to attribute names, attribute acquisition not cause, in turn thrown .
    • Unified package name in lower case, separated by breaks between there and only a semantic nature of English words. Unified package name singular form, but the class name if the plural, the plural form of the class name can be used.
      • Positive Example: Application of tools called packet com.alibaba.ai.util, class (the frame structure of the spring with reference to this rule) called MessageUtils
    • Avoid between sub parent class member variable, in exactly the same name or local variables between different code blocks, so reducing readability.
      • Description: subclass, the parent class members of the same variable names, type of variables even public is able to compile, local variables different code blocks in the same method with the same name is legitimate, but should be avoided. Parameter name for non setter / getter should also avoid the same member variable name.
      • Counterexample:

        public class ConfusingName {
            public int age;
            // 非setter/getter的参数名称,不允许与本类成员变量同名
            public void getData(String alibaba) {
                if(condition) {
                    final int money = 531;
                    // ...
                }
        
                for (int i = 0; i < 10; i++) {
                    // 在同一方法体中,不允许与其它代码块中的money命名相同
                    final int money = 615;
                    // ...
                }
            }
        }
        
        class Son extends ConfusingName {
            // 不允许与父类的成员变量名称相同
            public int age;
        }
    • Eliminate completely non-standard abbreviations, meaning I do not know to avoid looking text.
      • Anti Example: AbstractClass "abbreviated" named as AbsClass; condition "abbreviated" named as condi, such random Acronym seriously degrades the readability of the code.
    • For Service and DAO classes, based on the concept of SOA, must be exposed service interfaces, internal interfaces of the implementation class with the suffix Impl the difference.
      • Positive Example: CacheServiceImpl CacheService implement the interface.
  • recommend
    • In order to achieve the object code self-explanatory, any custom programming elements in the name, try to use the full word combinations to express its meaning.
      • Positive Example: in the JDK, expressed atoms updated class named: AtomicReferenceFieldUpdater.
      • Anti Example: int a manner to be named.
    • When naming constants and variables, indicating the type of nouns ending in order to enhance the degree of recognition.
      • 正例:startTime / workQueue / nameList / TERMINATED_THREAD_COUNT
      • 反例:startedAt / QueueOfWork / listName / COUNT_TERMINATED_THREAD
    • If the modules, interfaces, classes, methods of using the design pattern, the need to reflect the specific naming pattern.
      • Description: A design pattern is reflected in the name, help the reader quickly understand the architectural design concept.
      • 正例: public class OrderFactory; public class LoginProxy; public class ResourceObserver;
    • The interface class attributes and methods do not add any modification symbols (public and do not add), maintaining simplicity code, combined with effective and Javadoc comments. Try not defined in the interface in variable, if we must define a variable, it is certainly related to the interface method, and is the basis for constant throughout the application.
      • Example n: an interface method signature void commit (); interface base constant String COMPANY = "alibaba";
      • Counterexample: interface methods defined public abstract void f ();
      • Description: JDK8 interfaces allow a default implementation, then the default method is the default for all classes have realized the value of implementation.
    • If the interface name to describe the ability to take corresponding adjective for the interface name (usually -able adjectives).
      • Positive Example: AbstractTranslator Translatable implement the interface.
  • reference
    • Enum class name to bring Enum suffix, enumeration member name needs to be in all uppercase, separated by an underscore between words.
      • Description: Enumeration is actually a special class, domain members are constants, and is forced to default constructor is private.
      • Positive examples: enum name as a member of ProcessStatusEnum name: SUCCESS / UNKNOWN_REASON.
    • The layers naming convention:
      • A) -Service / naming convention method of the DAO layer
        • 1) A method of obtaining a single object with a prefixed get.
        • 2) a method of obtaining a plurality of prefixed objects, such as the use forms plural ending list: listObjects.
        • 3) obtain a statistical value of the method prefixed with count.
        • Four) insertion method of prefixed with save / insert.
        • 5) method to remove prefixed with remove / delete.
        • 6) using the modified method prefixed update.
      • B) domain model naming conventions
        • 1) Data Objects: xxxDO, xxx is the table name.
        • 2) Data Transfer Object: xxxDTO, xxx is the name associated with the business.
        • 3) display objects: xxxVO, xxx generally page name.
        • 4) POJO is DO / DTO / BO / VO collectively prohibited named as xxxPOJO.

2. Constant Defined

  • Enforcement
    • Do not allow any mana (ie without predefined constants) directly in the code.
      • Counterexample:

        String key = "Id#taobao_" + tradeId;
        cache.put(key, value);
        // 缓存get时,由于在代码复制时,漏掉下划线,导致缓存击穿而出现问题
    • When long or Long assignment, after the value of the use of capital L, not lowercase l, lowercase easily confused with the number 1, misleading.
      • Description: Long a = 2l; 21 is written, or the Long type 2 numbers.
  • recommend
    • Do not use a constant maintenance of all class constants, according to Constant function to classify, separate maintenance.
      • Description: large and constant class, disorganized, use the Find function to locate to modify constants, is not conducive to understand and maintain.
      • Example n: constants in the class buffer related CacheConsts; correlation constants in the system configuration based ConfigConsts.
    • Constant multiplexing hierarchy has five: the constant cross-application sharing, application sharing within a constant, constant share within the sub-project, sharing the bag constant, constant sharing within the class.
      • 1) Cross-application sharing constants: placed second party libraries, usually under the constant client.jar directory.
      • 2) Application of the shared constant: one is placed in the library, usually under constant sub-module directory.
        • Anti Example: we also need to understand the variables defined as the constant application sharing, two engineers, two classes are defined in a "YES" variable: in class A: public static final String YES = "yes"; in class B: public static final String YES = "y"; A.YES.equals (B.YES), is expected to be true, but the actual returns false, the line leading to the problem.
      • Internal 3) sub-project shared constant: that in the current sub-project of the constant directory.
      • 4) Constant shared encapsulated: i.e., under a separate directory under constant current package.
      • 5 shared constant) categories: direct private static final class is defined inside.
    • If the variable value varies only within a fixed range defined by enum types.
      • Note: If the name of the extended attribute exists outside the enum type should be used, the following figure is the embodiment is an extension information indicating the first several seasons of the year.
      • Positive examples:

        public enum SeasonEnum {
          SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4);
        
          private int seq;
          SeasonEnum(int seq) {
            this.seq = seq;
          }
          public int getSeq() {
            return seq;
          }
        }

3. Code format

  • Enforcement
    • If the braces is empty, {} can be written as simple, intermediate brackets without replacing the lines and spaces; if the block is not empty:
      • 1) does not wrap before the opening brace.
      • 2) After the opening brace wrap.
      • 3) before the closing brace wrap.
      • 4) After the closing brace else there is no line feed code, etc.; a rear right brace must wrap termination.
    • Space does not occur between the left parenthesis and character; likewise, there occurs a space between the right parenthesis and character; and before the opening brace needs space. Founder embodiment prompt see Section 5.
      • Anti Example: if (a == b blank spaces)
    • All must be a space between the if / for / while / switch / do and other reserved words and brackets.
    • Any two items, ternary operator needs both sides of a space.
      • Description: operators include assignment operators =, logical operators &&, arithmetic symbols.
    • With four spaces to indent, prohibit the use of tab characters.
      • Note: If you use the tab indentation, you must set a tab as four spaces. When IDEA setting tab is four spaces, do not check the Use tab character; while in eclipse, you must check the insert spaces for tabs.
      • Positive Example: (involving 1-5 points)

        public static void main(String[] args) {
          // 缩进4个空格
          String say = "hello";
          // 运算符的左右必须有一个空格
          int flag = 0;
          // 关键词if与括号之间必须有一个空格,括号内的f与左括号,0与右括号不需要空格
          if (flag == 0) {
            System.out.println(say);
          }
          // 左大括号前加空格且不换行;左大括号后换行
          if (flag == 1) {
            System.out.println("world");
          // 右大括号前换行,右大括号后有else,不用换行
          } else {
            System.out.println("ok");
          // 在右大括号后直接结束,则必须换行
          }
        }
    • There is only one space between the double slash comment and annotation content.
      • Positive Example: String param = new String (); // this is an example comment, note that there is a space after the double slash
    • During casts, braces between the right and need not cast any value separated by spaces.
      • 正例: long first = 1000000000000L; int second = (int)first + 2;
    • Single line not limit the number of characters than 120, more than necessary wrap, line feed the following principles:
      • 1) relative to the first line of a second row indented four spaces, starting from the third row, no further retracted, the reference example.
      • 2) below the operator wraps together.
      • 3) method call point below newline symbols together.
      • 4) a plurality of parameters of the method call requires the newline is carried out after the comma.
      • 5) Do not wrap before the parentheses, see counterexample.
      • Positive examples:

        StringBuilder sb = new StringBuilder();
        // 超过120个字符的情况下,换行缩进4个空格,点号和方法名称一起换行
        sb.append("Jack").append("Ma")...
            .append("alibaba")...
            .append("alibaba")...
            .append("alibaba");
      • Counterexample:

        StringBuilder sb = new StringBuilder();
        // 超过120个字符的情况下,不要在括号前换行
        sb.append("Jack").append("Ma")...append
            ("alibaba");
        // 参数很多的方法调用可能超过120个字符,不要在逗号前换行
        method(args1, args2, args3, ...
            , argsX);
    • When defining method parameters and pass multiple parameters must be a space behind the comma.
      • Positive examples: Examples args1 the argument, there must be a space behind. method (args1, args2, args3);
    • IDE's text file encoding to UTF-8; line breaks in the IDE using the Unix file format, do not use the Windows format.
  • recommend
    • Number of rows of individual methods is not more than 80 rows.
      • Note: In addition to the annotated method signature, number of rows around braces, within method code, blank lines, carriage returns, and any non-visible characters of no more than 80 lines.
      • Example n: code logic distinguish flowers and green leaves, individuality, and common, it becomes a single logical leafy additional methods to make the code clearer trunk; common become common method of extracting a logical, easy maintenance and reuse.
    • No need to increase a number of spaces to make the assignment variable equals equals aligned with the position corresponding to one line.
      • Positive examples:

        int one = 1;
        long two = 2L;
        float three = 3F;
        StringBuilder sb = new StringBuilder();
      • Description: sb increase this variable, if you want to align, then to one, two, three should increase the number of spaces in a relatively large number of variable circumstances, it is very cumbersome thing.
    • Different logical, inserted between the different semantics of different service codes separated by a blank line to improve readability.
      • Description: any case, there is no need to insert a plurality of spaced-blank lines.

4. OOP Statute

  • Enforcement
  • recommend
  • reference

The process set

  • Enforcement
  • recommend
  • reference

6. Concurrent Processing

  • Enforcement
  • recommend
  • reference

7. Control statements

  • Enforcement
  • recommend
  • reference

    8. Notes Statute

  • Enforcement
  • recommend
  • reference

9. Other

  • Enforcement
  • recommend
  • reference

Guess you like

Origin www.cnblogs.com/wyp1988/p/11970607.html