Java Backend Development Specification

Based on Alibaba JAVA development specification

The naming style

  1. [Mandatory] The class name uses the UpperCamelCase style and must follow the camel case, with the following exceptions: DO / BO / DTO / VO / AO

    正例:MarcoPolo / UserDO / XmlService / TcpUdpDeal / TaPromotion
    反例:macroPolo / UserDo / XMLService / TCPUDPDeal / TAPromotion

  2. [Mandatory] The method name, parameter name, member variable, and local variable all use the lowerCamelCase style, which must follow the camel case.

    正例: localValue / getHttpMessage() / inputUserId

  3. [Mandatory] The names of constants are all uppercase, and the words are separated by underscores. The semantic expression should be complete and clear, and the names should not be too long.

    Normal example: MAX_STOCK_COUNT Counterexample: MAX_COUNT

  4. [Mandatory] The name of the abstract class starts with Abstract or Base; the name of the exception class starts with Exception; the name of the test class starts with the name of the class to be tested and ends with Test.

  5. [Mandatory] Do not add is to the Boolean type variables in the Model class, otherwise some framework parsing will cause serialization errors.

    Counter example: the property defined as the basic data type Boolean isDeleted;, its method is also isDeleted(). When the RPC framework is performing reverse parsing, it "thinks" that the corresponding property name is deleted, so that the property cannot be obtained, and an exception is thrown .

  6. [Mandatory] For Service and DAO classes, based on the SOA concept, the exposed service must be an interface, and the internal implementation class is distinguished from the interface by the suffix of Impl. Positive example: CacheManagerImpl implements the CacheManager interface.

  7. [Recommended] In order to achieve the goal of self-explanatory code, when naming any custom programming element, use as complete a word combination as possible to express its meaning.

Positive example: The class that pulls the code from the remote repository is named PullCodeFromRemoteRepository Negative
example: the arbitrary naming method of the variable int a;.

  1. [Recommended] Do not add any modifier symbols (nor public) to the methods and properties of the interface class, keep the code concise, and add valid Javadoc comments. Try not to define variables in the interface. If you must define variables, they must be related to interface methods and are the basic constants of the entire application.

Positive example: Interface method signature: void f(); Interface basic constant representation: String COMPANY = "alibaba"; Negative
example: Interface method definition: public abstract void f();
Explanation: Interfaces in JDK8 allow default implementations, then this default method, which is the default implementation of value to all implementing classes.

  1. [Reference] Enumeration class names are recommended to be suffixed with Enum. Enumeration member names need to be all uppercase, and words should be separated by underscores.
    Note: Enumerations are actually special constant classes, and the constructor is forced to be private by default.
    Positive example: Enumeration name ProcessStatusEnum member name: SUCCESS / UNKOWN_REASON.

  2. [Reference] Naming conventions for each layer:
    A) Service/DAO layer method naming convention
    1) The method of obtaining a single object is prefixed with get.
    2) The method of obtaining multiple objects is prefixed with list.
    3) The method of obtaining the statistical value is prefixed with count.
    4) Insert methods are prefixed with save/insert.
    5) The delete method is prefixed with remove/delete.
    6) The modified method is prefixed with update.

2. Variable Definition

  1. [Recommended] Do not use a constant class to maintain all constants, classify them according to their functions, and maintain them separately. Note: The constant class is large and comprehensive, and it is necessary to use the search function to locate the modified constant, which is not conducive to understanding and maintenance.

Positive example: cache-related constants are placed under the class CacheConsts; system configuration-related constants are placed under the class ConfigConsts.

3. Code format

  1. [Mandatory] Use conventions for curly braces. If the curly bracket is empty, it can be written as {} succinctly, and no line break is required; if it is a non-empty code block:
    1) No line break before the opening curly bracket.
    2) Newline after opening brace.
    3) Newline before closing brace.
    4) If there are codes such as else after the closing curly bracket, the line will not be broken, which means that the closing curly bracket must be broken.

  2. [Mandatory] There is no space between the opening parenthesis and the character; similarly, there is no space between the closing parenthesis and the character.
    Counter example: if (space a == b space)

  3. [Mandatory] Spaces must be added between reserved words such as if/for/while/switch/do and parentheses.

  4. [Mandatory] A space must be added to the left and right sides of any binary or ternary operator.
    Note: Operators include assignment operator =, logical operator &&, addition, subtraction, multiplication and division symbols, etc.

  5. [Mandatory] Use 4 spaces for indentation, and tab characters are prohibited.
    Description: The Vue project is indented with 2 spaces

  6. [Mandatory] There is one and only one space between the double slash of the comment and the comment content.
    Positive example: // Comment content, note that there is a space between // and the comment content.

  7. [Mandatory] When defining and passing in method parameters, a space must be added after the commas of multiple parameters.
    Positive example: The "a" of the actual parameter in the following example must be followed by a space. method("a", "b", "c");

  8. [Mandatory] The text file encoding of the IDE is set to UTF-8; the newline character of the file in the IDE uses the Unix format, not the Windows format.

  9. [Recommended] Insert a blank line between the execution statement group, variable definition statement group, different business logic or different semantics in the method body. Blank lines do not need to be inserted between the same business logic and semantics.
    Description: It is not necessary to insert multiple blank lines to separate them.

4. OOP protocol

  1. [Mandatory] All overriding methods must be annotated with @Override.

  2. [Mandatory] Obsolete classes or methods cannot be used.

  3. [Mandatory] The equals method of Object is prone to throwing null pointer exceptions. You should use constants or objects with certain values ​​to call equals.
    Positive example: "test".equals(object);
    Negative example: object.equals("test");

  4. [Mandatory] All values ​​of the same type of wrapper objects are compared using the equals method.
    Description: For the assignment of Integer var = ? in the range of -128 to 127, the Integer object is generated in IntegerCache.cache, and the existing object will be reused. The Integer value in this range can be directly judged by ==, but this range All other data will be generated on the heap and will not reuse existing objects. This is a big pit. It is recommended to use the equals method for judgment.

  5. [Mandatory] Return values ​​and parameters of RPC methods must use wrapper data types.

  6. [Mandatory] It is forbidden to add any business logic in the constructor. If there is initialization logic, please put it in the init method.

  7. [Recommended] When a class has multiple constructors, or multiple methods with the same name, these methods should be placed together in order for easy reading.

  8. [Recommended] In the loop body, use the append method of StringBuilder to extend the connection method of strings. Description: The decompiled bytecode file shows that a new StringBuilder object will be generated each time the loop is performed, and then the append operation is performed, and finally the String object is returned through the toString method, resulting in a waste of memory resources.
    Counter example:

  String str = "start";
  for (int i = 0; i < 100; i++) { str = str + "hello"; } 
  1. [Recommended] Use the clone method of Object with caution to copy objects. Note: The clone method of an object is a shallow copy by default. If you want to implement a deep copy, you need to override the clone method to copy the attribute object.

5. Collection processing

  1. [Mandatory] To use the method of converting a set to an array, you must use the toArray(T[] array) of the set, and the incoming array is the exact same type, and the size is list.size().
    Description: When using the toArray method with parameters, when the array space allocated by the input parameter is not large enough, the toArray method will re-allocate the memory space and return the new array address; if the array elements are larger than the actual needs, the subscript is [ list.size() The array elements of ] will be set to null, and other array elements will keep their original values, so it is best to define the size of the method input parameter group to be consistent with the number of collection elements. Positive example:
List<String> list = new ArrayList<String>(2);
list.add("guan");
list.add("bao");
String[] array = new String[list.size()]; array = list.toArray(array); 

Counter example: There is a problem in directly using the toArray no-parameter method. The return value of this method can only be the Object[] class. If you cast other types of arrays, a ClassCastException error will occur.

  1. [Mandatory] Do not perform remove/add operations on elements in a foreach loop. Please use the Iterator method to remove elements. If you operate concurrently, you need to lock the Iterator object.
    Positive example:
  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
      String item = iterator.next();
      if (删除元素的条件) {
        iterator.remove();
      }
  }

Counterexample:

  List<String> list = new ArrayList<String>();
  list.add("1");
  list.add("2");
  for (String item : list) {
    if ("1".equals(item)) { list.remove(item); } } 
  1. [Recommended] Use entrySet to traverse the Map class set KV instead of keySet.

6. Control Statements

  1. [Mandatory] 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 has no code.

  2. [Mandatory] Braces must be used in if/else/for/while/do statements. Even if there is only one line of code, avoid single-line coding: if (condition) statements;

  3. [Recommended] In addition to common methods (such as getXxx/isXxx), do not execute other complex statements in conditional judgments, and assign the result of complex logical judgments to a meaningful Boolean variable name to improve readability. Explanation: The logic in many if statements is quite complex. The reader needs to analyze the final result of the conditional expression to determine what kind of statement is executed under what condition. Then, what if the reader analyzes the logical expression incorrectly?
    Positive example: // The pseudo code is as follows

final boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
if (existed) { ... } 

Counterexample:

if ((file.open(fileName, "w") != null) && (...) || (...)) {
  ...
}
  1. [Recommendation] The performance of the statements in the loop body should be considered. The following operations should be moved outside the loop as much as possible, such as defining objects, variables, obtaining database connections, and performing unnecessary try-catch operations (whether this try-catch can be moved outside the loop? ).
  2. [Reference] Parameter verification is required in the following situations:
    1) A method with a low calling frequency.
    2) Methods with high execution time overhead. In this case, the parameter verification time is almost negligible, but if the intermediate execution is rolled back due to parameter errors, or errors are made, the gain is more than the loss.
    3) Methods that require extremely high stability and availability.
    4) The open interface provided externally, whether it is RPC/API/HTTP interface. 5) Sensitive permission entry.

7. Annotation Protocol

  1. [Mandatory] Comments on classes, class attributes, and class methods must use the Javadoc specification, use the /**content*/ format, and cannot use the //xxx method.

  2. [Mandatory] 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. Description: For the implementation requirements of subclasses, or the precautions for invocation, please explain together.

  3. [Mandatory] All classes must add creator and creation date.

  4. [Mandatory] A single-line comment inside the method, start a new line above the commented statement, and use // comment. Use /* */ for multi-line comments inside the method, pay attention to alignment with the code.

  5. [Mandatory] All enumeration type fields must have comments describing the purpose of each data item.

  6. [Recommendation] When the code is modified, the comments should also be modified accordingly, especially the modification of parameters, return values, exceptions, core logic, etc. Note: Code and annotation updates are out of sync, just like road network and navigation software updates are out of sync. If the navigation software is seriously lagging behind, the meaning of navigation will be lost.

  7. [Reference] Carefully comment out the code. Elaborate above instead of simply commenting out. Delete if useless.

  8. [Reference] Requirements for comments: first, to be able to accurately reflect the design ideas and code logic; second, to be able to describe the business meaning, so that other programmers can quickly understand the information behind the code. A large piece of code without comments is like a book for readers. Comments are for themselves. Even after a long time, they can clearly understand the thinking at that time; comments are also for successors, so that they can quickly replace their own. Work.

  9. [Reference] Good naming and code structure are self-explanatory, and comments strive to be concise, accurate, and expressive. Avoid an extreme of comments: too many comments, once the logic of the code is modified, it is a considerable burden to modify the comments.

  10. 【Reference】Special note mark, please indicate the mark person and mark time. Take care to deal with these marks in a timely manner, and frequently clean up such marks through mark scanning. Line failures sometimes originate from the code at these markers.
    1) TODO: (marked person, marked time, [expected processing time]) Indicates a function that needs to be implemented, but has not yet been implemented. This is actually a Javadoc tag, which is not currently implemented in Javadoc, but is widely used. Can only be applied to classes, interfaces and methods (as it is a Javadoc tag).
    2) Error, can't work (FIXME): (marked person, marked time, [estimated processing time]) In the comments with FIXME marked a code is wrong, and does not work, needs to be corrected in a timely manner.

8. Others

  1. [Mandatory] When using regular expressions, make good use of its pre-compilation function, which can effectively speed up regular expressions. Description: Do not define in the method body: Pattern pattern = Pattern.compile(rule);

  2. [Mandatory] Note that the Math.random() method returns a double type. Note that the value range is 0≤x<1 (zero value can be obtained, pay attention to the exception of division by zero). If you want to obtain a random number of integer type, do not use x is magnified several times by 10 and then rounded up, and directly use the nextInt or nextLong method of the Random object.

  3. [Mandatory] Get the current millisecond System.currentTimeMillis(); instead of new Date().getTime();

  4. [Recommended] The size of any data structure should be specified in the construction or initialization to prevent the data structure from growing indefinitely and eating up memory.

Nine, exception handling

  1. [Mandatory] The purpose of catching an exception is to handle it. Don't catch it and then throw it away. If you don't want to handle it, please throw the exception to its caller. The outermost business user must handle exceptions and convert them into content that users can understand.

10. MySQL database

create table specification

  1. [Mandatory] The table name and field name must use lowercase letters or numbers. It is forbidden to start with a number, and it is forbidden to have only numbers between two underscores. The modification of database field names is expensive, because pre-release cannot be performed, so field names need to be carefully considered.
    Note: MySQL is case-insensitive under Windows, but is case-sensitive by default under Linux. Therefore, database names, table names, and field names are not allowed to appear in any capital letters to avoid extraneous branches.
    Positive example: aliyun_admin, rdc_config, level3_name Counter example: AliyunAdmin, rdcConfig, level_3_name

  2. [Mandatory] Disable reserved words, such as desc, range, match, delayed, etc. Please refer to MySQL official reserved words.

  3. [Mandatory] The primary key index name is pk_field name; the unique index name is uk_field name; the common index name is idx_field name. Description: pk_ is primary key; uk_ is unique key; idx_ is short for index.

  4. [Mandatory] The decimal type is decimal, and the use of float and double is prohibited.

  5. [Mandatory] If the stored strings are nearly equal in length, use the char fixed-length string type.

  6. [Mandatory] varchar is a variable-length string, no storage space is allocated in advance, and the length should not exceed 5000. If the storage length is greater than this value, define the field type as text.

  7. [Mandatory] The table must have three fields: id, create_time, update_time, delete_flag

  8. [Mandatory] For fields of Boolean type, use decimal type

  9. [Mandatory] Comments are required for both tables and fields.

  10. [Recommended] Database sharding is recommended only when the number of rows in a single table exceeds 5 million or the capacity of a single table exceeds 2 GB. Note: If it is expected that the data volume in three years will not reach this level at all, please do not split the database and the table when creating the table.

  11. [Reference] Appropriate character storage length not only saves database table space and index storage, but more importantly, improves retrieval speed.

index reduction

  1. [Mandatory] A field with unique characteristics in business must be built into a unique index even if it is a combination of multiple fields.
    Note: Don't think that the unique index affects the insert speed. This speed loss can be ignored, but it is obvious to improve the search speed. In addition, even if a very perfect verification control is done at the application layer, as long as there is no unique index, according to Murphy's law, Dirty data must be generated.

  2. [Mandatory] Join is prohibited for more than three tables. For fields that need to be joined, the data types must be absolutely consistent; when querying multiple tables, make sure that the associated fields need to have indexes.
    Note: Pay attention to table indexes and SQL performance even in double-table joins.

  3. [Mandatory] When creating an index on a varchar field, the index length must be specified. It is not necessary to create an index on the entire field. The index length can be determined according to the actual text discrimination.
    Note: The length of the index and the degree of discrimination are a pair of contradictions. Generally, for string type data, the index with a length of 20 has a degree of discrimination of more than 90%. You can use count(distinct left(column name, index length))/ The discrimination of count(*) is determined.

  4. [Reference] Avoid the following extreme misunderstandings when creating an index:
    1) It is better to overuse than to lack. Think that a query needs to build an index.
    2) Rather lack rather than overuse. It is believed that indexes consume space and severely slow down updates and new additions.
    3) Resist unique indexes. It is believed that the uniqueness of the business needs to be solved by the method of "check first and then insert" at the application layer.

SQL statement

  1. [Mandatory] Do not use count (column name) or count (constant) to replace count(*). count(*) is the standard syntax for counting rows defined by SQL92, which has nothing to do with the database, and has nothing to do with NULL and non-NULL.
    Description: count(*) will count rows with NULL values, while count(column name) will not count rows with NULL values ​​in this column.

  2. [Mandatory] count(distinct col) calculates the number of unique rows except NULL in this column. Note that count(di col1, col2) returns 0 if one of the columns is all NULL, even if the other column has different values.

  3. [Mandatory] When the values ​​of a column are all NULL, the return result of count(col) is 0, but the return result of sum(col) is NULL.

  4. [Mandatory] Foreign keys and cascades must not be used, and all foreign key concepts must be resolved at the application layer.

  5. [Mandatory] The use of stored procedures is prohibited. Stored procedures are difficult to debug and extend, and have no portability.

  6. [Recommendation] Avoid the in operation if it can be avoided. If it cannot be avoided, you need to carefully evaluate the number of set elements behind in, and control it within 1000.

  7. [Reference] If there is a need for globalization, all characters are stored and represented in utf-8 encoding. Pay attention to the difference between characters.
    Description: SELECT LENGTH("Easy work"); The return is 12 SELECT CHARACTER_LENGTH("Easy work"); The return is 4 If you need to store expressions, then choose utfmb4 for storage, pay attention to the difference between it and -8 encoding.

  8. [Mandatory] When updating a data table record, the update_time field value corresponding to the record must be updated at the same time as the current time.

  9. [Reference] Do not abuse @Transactional transactions. Transactions will affect the QPS of the database. In addition, where transactions are used, various rollback schemes should be considered, including cache rollback, search engine rollback, message compensation, and statistical correction.


I have a WeChat public account, and I often share some dry goods related to Java technology; if you like my sharing, you can use WeChat to search for "Java Head" or "javatuanzhang" to follow.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772698&siteId=291194637