Ali Development Manual Specification (JAVA)

Table of contents

1. Programming protocol 

(1) Naming convention

(2) Constant definition

(3) Code format 

(4) OOP protocol

(5) Date and time

(6) Collection processing 

(7) Concurrent processing

(8) Control statement

(9) Notes and Statutes

(10) Front-end and back-end protocols

2. Exception log 

(1) Error code

(2) Exception handling

(3) Log protocol 

3. Unit testing 

4. Safety regulations

5. MySQL database 

(1) Table creation protocol

(2) Index Protocol 

(3) SQL statement

(4) ORM mapping

6. Engineering structure 

(1) Application layering

(2) Second-party library dependencies 

(3) Server 

7. Design Regulations 


1. Programming protocol 

(1) Naming convention

1. No name in the code can start with an underscore or a dollar sign, nor can it end with an underscore or a dollar sign. Counterexample : _name / __name / $name / name_ / name$ / name__.

2. It is forbidden to mix pinyin and English. Counter example : DaZhePromotion [discount] / getPingfenByName() [score].

3. Class names use the big camel case naming method; method names, parameter names, member variables, and local variables all use the small camel case naming method.

4. The names of constants are all capitalized, and words are separated by underscores; for example : MAX_STOCK_COUNT / CACHE_EXPIRED_TIME.

5. The type is followed by square brackets to indicate an array. Example : Define integer array int[] arrayDemo. 

6. For boolean type variables, do not start with is to avoid errors in the partial serialization framework. Counterexample : boolean isExists.

7. Put an end to completely non-standard abbreviations to avoid ignorance of the meaning. Counter-example : AbstractClass is "abbreviated" into AbsClass; condition is "abbreviated" into condi.

8. For Service and DAO classes, it must be an interface, and the implementation needs to end with the suffix of Impl. Different from interfaces
such as: CacheService CacheServiceImpl.

9. The enumeration class name is suffixed with Enum, and the enumeration member names need to be all uppercase, and the words are separated by underscores. 

10. Do not add any modifiers to the attributes and methods in the class interface.

(2) Constant definition

1. Do not allow any magic values ​​(that is, constants that are not predefined) to appear directly in the code.  Negative example : String key = "id=" + id;

2. When long and Long are initially assigned, uppercase must be used to avoid confusion with the number 1.
Example : Long a = 2L    Counter example : Long a = 2l

3. Do not use a constant class to maintain all constants, split and classify them according to functions as much as possible, and maintain them separately. Easy to understand and maintain.

(3) Code format 

1. If the curly braces are empty, just write {}, and there is no need for newlines and spaces between the curly braces; if it is a non-empty code block: (1) No newline before the left curly brace, and a newline after the left curly brace. (2) Line break before the closing curly brace.  

2. There is no space between the left parenthesis and the next character, and there is no space between the right parenthesis and the previous character
Example : if (flag == 0).

3. Spaces must be added between reserved words such as if/for/while/switch/do and the brackets. 

4. Any binary and ternary operators need to add a space on the left and right sides. 

5. There is only one space between the double slashes of the comment and the content of the comment. 

6. When method parameters are defined and passed in, spaces must be added after commas for multiple parameters. Example : method("a", "b", "c");

(4) OOP protocol

1. Use the class name directly to access a class's static variables or static methods.

2. All override methods must be annotated with @Override to accurately determine whether the override is successful.

3. External interfaces should avoid modification in principle, and new interfaces can be added. Outdated interfaces should be annotated with @Deprecated

4. The equals method of Object is easy to throw a null pointer exception, and you should use a constant or an object that is sure to have a value to call equals. Example : "test".equals(object); 

5. All value comparisons between integer wrapper objects shall be compared using the equals method. If == is used for judgment, there will be a limit to the value range.

6. String concatenation in the loop body, using the append method of StringBuilder.

7. It is forbidden to add any business logic in the construction method. If there is initialization logic, please put it in the init method. 

8. For the equivalence judgment between floating-point numbers, the basic data type cannot be compared with ==, and the package data type cannot be judged with equals. 

(5) Date and time

1. When formatting the date, the lowercase y is uniformly used to represent the year in the incoming pattern. 

2. Get the current milliseconds: System.currentTimeMillis(); instead of new Date().getTime(). 

(6) Collection processing 

1. Whenever equals is rewritten, hashCode must be rewritten.

2. To judge whether all the elements in the collection are empty, use the isEmpty() method instead of the size()==0 method.

3. The result of subList method of ArrayList cannot be converted into ArrayList. (subList returns the internal class of ArrayList, not ArrayList, and is a view of ArrayList. All operations on SubList will be reflected on the original list of ArrayList.)

4. To use the collection-to-array method, you must use the collection's toArray(T[] array).

5. Do not remove/add elements in the foreach loop. Please use the Iterator method to remove elements. If the operation is performed concurrently, you need to lock the Iterator object. 

6. When using the tool class Arrays.asList() to convert an array into a collection, methods related to modifying the collection cannot be used, such as: add/remove/clear will throw an UnsupportedOperationException exception.

(7) Concurrent processing

1. Obtaining a singleton object needs to ensure thread safety, and the methods in it must also ensure thread safety. 

2. Thread resources must be provided through the thread pool, and it is not allowed to explicitly create threads in the application, so as to avoid creating too many threads and reduce the overhead of creating and destroying threads.

3. Thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. The disadvantage of the thread pool objects returned by Executors is that a large number of threads may be created or a large number of requests may be accumulated, resulting in OOM.

4. For concurrency, consider the performance loss of locks. If you can lock without a lock, you don’t need a lock; if you can lock a block, don’t lock the entire method; if you can lock an object, don’t lock a class.

5. When locking multiple resources, database tables, and objects at the same time, it is necessary to maintain a consistent locking sequence, otherwise deadlock may occur.

6. If the probability of access conflict is not high, it is recommended to use optimistic locking.

7. When the capacity of HashMap is not enough to resize, due to high concurrency, there may be a dead link, causing the CPU to soar. Pay attention to avoiding this risk during the development process. 

8. It is recommended to use static modification for ThreadLocal object

(8) Control statement

1. In the switch block, each case is either terminated by break/return, or a comment indicates which case will be executed; a switch must contain default, even if it is empty.

2. When the variable type in the brackets of the switch is String and this variable is an external parameter, a null judgment must be made first.

3. Braces must be used in if/else/for/while/do statements. 

4. In high-concurrency scenarios, avoid using "equal to" judgments as interrupt or exit conditions. Counter-example : When it is judged that the remaining number of prizes is equal to 0, the distribution of prizes is terminated, but due to a concurrent processing error, the number of prizes instantly becomes negative. In this case, the activity cannot be terminated. 

(9) Notes and Statutes

1. Comments on classes, class attributes, and class methods must use the Javadoc specification, use the /**content*/ format, and do not use the // xxx method.

2. All abstract methods (including methods in interfaces) must be annotated with Javadoc

3. All classes must add creator and creation date. 

(10) Front-end and back-end protocols

1. The API for front-end and back-end interaction needs to specify the protocol, domain name, path, request method, request content, status code, and response body.

2. The interface related to the front-end and back-end data lists is returned. If it is empty, an empty array [] or an empty collection {} will be returned. 

3. When an error occurs on the server side, the response information returned to the front end must include four parts: HTTP status code, errorCode, errorMessage, and user prompt information.

2. Exception log 

(1) Error code

1. The error code does not reflect the version number and error level information. 

2. The error code cannot be directly output to the user as a prompt message. 

(2) Exception handling

1. Do not catch runtime exceptions inherited from RuntimeException. Such exceptions need to be checked and avoided by themselves, such as: IndexOutOfBoundsException / NullPointerException.

2. Do not use it for process control or conditional control after the exception is caught. 

3. The purpose of catching an exception is to handle it. Don't catch it but throw it away without processing anything. If you don't want to handle it, please throw the exception to its caller.

4. The finally block must close the resource object and stream object, and try-catch if there is an exception; do not use return in the finally block. 

(3) Log protocol 

1. Do not use the log implementation class, but use the API interface of SLF4J, use the facade mode, and it is easy to achieve a unified log processing method for all classes.

2. All log files are kept for at least 15 days, because some abnormalities have the characteristics of "weekly" occurrence frequency.

3. To avoid printing logs repeatedly and wasting disk space, be sure to set additivity=false in the log configuration file. 

4. When printing logs, it is forbidden to directly use JSON tools to convert objects into Strings.

3. Unit testing 

1. A good unit test must abide by the AIR principle, that is, it has the characteristics of automation, independence, and repeatability.

2. Unit tests can be executed repeatedly and cannot be affected by the external environment. 

3. Keep unit tests independent. In order to ensure that unit tests are stable, reliable and easy to maintain, unit test cases must not call each other, nor can they rely on the order of execution. 

4. Safety regulations

1. Pages or functions that belong to the user must undergo permission control verification. 

2. Direct display of user sensitive data is prohibited, and the display data must be desensitized. 

3. The SQL parameters entered by the user are strictly limited by parameter binding or METADATA field values ​​to prevent SQL injection and prohibit string splicing SQL to access the database. 

4. Forms and AJAX submissions must perform CSRF security verification. 

5. MySQL database 

(1) Table creation protocol

1. The field that expresses the concept of yes or no must be named in the form of is_xxx, and the data type is unsigned tinyint (1 means yes, 0 means no). 

2. The field name of the table name must use lowercase characters or numbers; the beginning of a number is prohibited, and only numbers between two underscores are prohibited. Example : aliyun_admin, rdc_config, level3_name.

3. Disable reserved words, such as desc, range, match, delayed, etc.

4. Table names do not use plural nouns. 

5. 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. Note: pk_ is the primary key; uk_ is the unique key; idx_ is the abbreviation of index. 

6. The decimal type is decimal, and float and double are prohibited. 

7. If the lengths of the stored strings are almost equal, use the char fixed-length string type.

8. Varchar is a variable-length character string, and the length should not exceed 5000. If the storage length exceeds this value, use text and list it independently.

9. The table must have three fields: id, create_time, update_time. 

(2) Index Protocol 

1. Fields with unique characteristics in business, even composite fields, must be built into a unique index. 

2. Join is prohibited for more than three tables. The data types of the fields that need to be joined must be absolutely consistent; when multi-table association queries, ensure that the associated fields need to have indexes.

3. When creating an index on a varchar field, the index length must be specified. It is not necessary to create an index for the entire field, and the index length is determined according to the actual text discrimination. 

4. Left blur or full blur is strictly prohibited.

5. Use the covering index to perform query operations to avoid returning to the table. 

(3) SQL statement

1. 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. 

2. 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, so pay attention to the NPE problem when using sum(). 

3. Avoid the in operation if it can be avoided. If it is really unavoidable, you need to carefully evaluate the number of set elements behind the in and control it within 1000. 

(4) ORM mapping

1. In the table query, never use * as the field list of the query, and which fields are required must be clearly stated.

2. The Boolean attribute of the POJO class cannot add is, but the database field must add is_, which requires mapping between fields and attributes in resultMap. 

3. Use of sql.xml configuration parameters: #{}, #param# Do not use ${} This method is prone to SQL injection.

4. 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. 

6. Engineering structure 

(1) Application layering

1. Hierarchical domain model specification: 
• DO (Data Object): This object corresponds to the database table structure one by one, and the data source object is transmitted upward through the DAO layer. 
• DTO (Data Transfer Object): data transfer object, the object that Service or Manager transfers out. 
• BO (Business Object): Business object, an object that encapsulates business logic that can be output by the Service layer. 
• Query: data query object, each layer receives the query request from the upper layer. Pay attention to the query encapsulation with more than 2 parameters, it is forbidden to use the Map class to transfer. 
• VO (View Object): Display layer object, usually the object transmitted from the Web to the template rendering engine layer. 

(2) Second-party library dependencies 

1. The naming method of the version number of the second-party library: major version number. minor version number. revision number.

2. The enumeration type can be defined in the second-party library, and the parameter can use the enumeration type, but the interface return value does not allow the use of the enumeration type or POJO objects containing the enumeration type. 

3. When relying on a second-party library group, a unified version variable must be defined to avoid inconsistent version numbers. 

4. It is forbidden to have the same GroupId, the same ArtifactId, but different Versions in the pom dependencies of sub-projects.

(3) Server 

1. For high-concurrency servers, it is recommended to reduce the time_wait timeout of the TCP protocol.

2. Set the -XX:+HeapDumpOnOutOfMemoryError parameter to the JVM environment parameter to let the JVM output dump information when it encounters an OOM scene.

7. Design Regulations 

1. In the requirement analysis stage, if there are more than one type of User interacting with the system and more than five related User Cases, use a use case diagram to express clearer structured requirements. 

2. If a business object has more than 3 states, use a state diagram to express and clarify each trigger condition of the state change.

Guess you like

Origin blog.csdn.net/weixin_51360584/article/details/128098109