Location>code7788 >text

JAVA development specification

Popularity:120 ℃/2024-11-14 16:48:40

preamble

The purpose of this specification is to improve the quality of code, improve the efficiency of teamwork, the specification appears in the mandatory, recommended, reference to the meaning of the following:

[Mandatory]: Must be strictly adhered to, and if there are any special circumstances, the Architecture Committee will need to review and report.

【Recommendation】:No special circumstances must be followed, with the permission of the development team leader may not be followed.

[Reference]: Can be used for reference, not strictly required.

Backend development specification

1.1 Naming conventions

  1. [Mandatory] Hump naming, otherwise not allowed, except for constants.

  2. [Mandatory] Mixing pinyin and English is not allowed.

    Example: alibaba / taobao / youku / hangzhou etc. Internationally recognized names can be treated as English.
    Counterexamples: DaZhePromotion [ discount ] / getPingfenByName() [ rating ]
    
  3. [Mandatory] Constants are capitalized, words are separated by underscores, and semantics are as complete as possible, e.g., MAX is semantically ambiguous.

     Positive Example: MAX _STOCK_COUNT
     Counterexample: MAX_COUNT
    
  4. Mandatory] Abstract classes start with Abstract or end with Base, Exception classes end with Exception, and Test classes start with the name of the class it is testing and end with Test.

  5. [Mandatory] Word abbreviations are not allowed unless they are common industry abbreviations.

     Counter-examples: AbstractClass is "abbreviated" to AbsClass; condition is "abbreviated" to condi, and this kind of arbitrary abbreviation seriously reduces the readability of the code.
    
  6. Recommended] tool class ends with Utils, help class ends with Helper, help class with the difference between the tool class is to help the class is convenient for the use of business logic, tool class is more general.

     Example: An application toolkit named com . yujiahui . common . util, class named MessageUtils (this rule refers to the spring framework structure)
    
  7. [Recommended] Enumeration classes use Enum endings.

  8. [Recommended] If a module, interface, class, or method uses a design pattern, reflect the specific pattern in the naming.

     Description: Embody the design pattern in the name, which is conducive to the reader to quickly understand the architectural design concepts.
     Example: public class OrderFactory; public class LoginProxy; public class LoginProxy
     public class LoginProxy.
     public class ResourceObserver.
    
  9. [Reference] Layered naming convention

      1. DTO naming conventions , if the DTO is a command , the end of Cmd , if it is a query , Query end , if it is a view object , VO end , other can not be categorized DTO end .
      2. Service layer ends with Service and Dao layer ends with Dao. Methods to get a single object to start with get, get multiple objects to start with list, get the number has count to start.
          Insert starts with create, update starts with update, and delete starts with delete.
      3. domain layer factory to Factory at the end of the domain service is recommended to DomainService at the end of the entity and the value of the object does not need to be suffixed, what is the name of what name, such as the order entity is called Order
      4. domain model layer naming try to be consistent with the data table, such as the table order_detail, named OrderDetail, if the table has a unified prefix, whether the prefix is reflected in the name of the model object in a unified project.
    
  10. [Recommended] entity inside some Boolean methods if you start with is easy to be judged by the framework as a property, it is recommended that they all start with iz, such as izEasy.

1.2 Constant specification

  1. [Mandatory] Devil's numbers are not allowed.

  2. Mandatory] When assigning a value to a long or Long, use an uppercase L, not a lowercase l. Lowercase is easily confused with the number 1, which can lead to misunderstandings.

    Explanation: Long a = 2 l; Write the number 21, or the Long type 2?
    
  3. Don't maintain all constants in one class, for example, the constants of the domain model can be put inside the domain model, or you can create a separate constant class, the constant class ends with Constants.

     Example: Cache-related constants are placed in class CacheConstants; system configuration-related constants are placed in class ConfigConstants.
    
  4. [Recommendation] Constant class sharing should be placed in a hierarchy, which is divided into: cross-application sharing, in-application sharing, in-module sharing, and in-class sharing. Constant classes shared across applications are placed under a jar's constant package, constant classes shared within an application are placed under a common module's constant package, and constant classes shared within a module are placed under the module's constant package.

    Counter-example: Easy-to-understand variables should also be defined uniformly as in-application shared constants, and the two tappers have defined "yes" variables in each of the two classes:
     In class A: public static final String YES = " yes "; in class B: public static final String YES = " yes ".
     Class B: public static final String YES = " y " ; A .
     A . YES . equals(B . YES), which is expected to be true but actually returns false, causing problems on the wire.
    

1.3 Formatting norms

  1. [Mandatory] The first curly bracket is not a newline, 120 characters on a single line, and the rest is in the IDE default format.
  2. [Recommended] Blank lines are required between code with different business logic or different semantics.
  3. [Mandatory] IDE sets the file encoding to UTF-8.
  4. [Mandatory] Multiple variables are not allowed to be defined on a single line.

1.4 Java specification

  1. [Mandatory] All overridden methods must add @Override.

  2. [Recommended] equals method is easy to report null pointer exception, constants put in front or use (jdk7 introduced).

     Positive example: " test " .equals(object);
     Counterexample: ( " test " ).
    
  3. [Mandatory] Equal comparisons of wrapper classes use equals, not ==.

  4. [Recommendations] Criteria for the use of basic types and package types:

      1. attributes of pojo types with wrapper types
      2. wrapper types for parameters and return values of RPC methods
      3. basic types for local variables
    
  5. [Mandatory] Domain model classes must implement toString method

  6. The order of method definitions within a class is: public method, protected method, private method, getter, setter.

  7. [Recommended] The access control of the methods of a class is strict. Methods of a class are only used internally and must be private, only open to inherited classes and must be protected, and variables are similar to methods.

  8. [Mandatory] Don't use static variables to store data inside a class, and if needed, use thread-safe data structures.

  9. [Mandatory] You can't delete collection elements in a foreach loop; delete elements using an iterator.

    	// Positive Case
        Iterator<String> iterator = ();
        while (()) {
                String item = ();
                if (Conditions for deleting elements) {
                        ();
                }
        }
    
    	// counter case
         List<String> a = new ArrayList<String>();
            ("1");
            ("2");
            for (String item : list) {
                    if ("1".equals(item)) {
                            (item);
                    }
            }
    
  10. [Mandatory] SimpleDateFormat thread-unsafe Do not define as static variable.

     	// standard practice:Watch out for thread safety!,utilization DateUtils 。The following treatment is also recommended:
        private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
                @ Override
                protected DateFormat initialValue() {
                        return new SimpleDateFormat("yyyy-MM-dd");
                }
        };
    
  11. [Recommendation] When high concurrency, consider the performance of the lock, try to use lock-free data structures, can lock the block do not lock the entire method, can lock the object and do not lock the entire class.

  12. Forced] There are concurrent modification of the same object scenarios, you need to lock, concurrent modification of the probability is greater than 20%, the use of pessimistic locks, otherwise the use of optimistic locks, optimistic locks according to the business scenarios to consider the number of retries.

  13. [Recommendation] Try not to modify the input parameters of functions with return values.

  14. [Recommended] Use else as little as possible and use guard statements. For example: if(condition) {return obj;} other logic; If there are really many if-else, use state mode.

        // Positive example: if-else logic with more than 3 levels can be implemented using guard statements, policy patterns, stateful patterns, etc...
        public void today() {
            if (izBusy()) {
                ("change time."); return; { if (izBusy()) { if (izBusy())
                return.
            }
            if (izFree()) {
                ("go to travel."); return; } if (izFree()) { ("go to travel."); }
                return; }
            }
            return; }
        }
    

1.5 Operational code specifications

  1. The [mandatory] method is not allowed to have more than 5 parameters.

  2. [Recommended] Do not use generalized parameters like Map for parameters and return values.

  3. [Mandatory] The curly bracket level of the method is not allowed to exceed 4 levels.

  4. [Recommended] A method does only one thing, and the method does not exceed 30 lines.

  5. [Mandatory] Methods must not have side effects, such as query class methods, and are not allowed to change the value of an attribute of an incoming parameter.

  6. The [Recommended] category cannot exceed 500 lines.

  7. [Recommended] Do not allow a lot of duplicate code.

  8. [Mandatory] Batch operations must be grouped, such as batch insertion of one thousand pieces of data into a group of 500.

 Positive example: List groups = (list,500);
  1. [Mandatory] Business queries return too much data must be paged, such as not more than 5000 return data.

  2. Recommended] tools to see if the project is provided, not allowed to add at will, if you encounter the project and the jar within the same name tool class, give priority to the use of the project's class, such as StringUtils in more than one jar, the first use of the project's StringUtils, to meet the requirements, and then use other jar classes or transplant methods to the project's StringUtils.

  3. [Recommended] Important business processes must have business logs, using BizLog annotations to record old and new values.

  4. [Recommended] Service layer provides are business logic methods, do not put a large number of query methods, there are a variety of query business model extracted from the Query class, such as OrderQueryService, you can also use the CQRS model, the separation of command and query.

  5. [Mandatory] Business scenarios where concurrent operations exist, consider method idempotency, or use optimistic locking.

  6. [Recommendation] Always refactor your code to avoid code corruption and remove the next time mentality (subtext: never change again).

  7. [Mandatory] When the business involves exporting and uploading security-sensitive data files such as orders, user information, amounts, etc. to AliCloud OSS, it is mandatory to use the file service of the/api/file/uploadPrivateinterface to upload to the AliCloud OSS.

  8. [Mandatory] Business logic try to avoid cross-database transaction operations, it is strictly prohibited to intersperse the execution of different databases in the transaction of the sql statement, if necessary, to consider the failure scenarios to compensate for the program and the alarm mechanism.

    Counterexample:
    Execute A database update logic X
    Execute B database update logic Y
    Execute A database update logic X
    Execute B database update logic Y
    

1.6 Exception specification

  1. [Recommended] Do not allow try-catch on large pieces of code.
  2. [Mandatory] For dead loop threads with core functionality must try-catch the entire loop body to prevent any exceptions leading to the exit of the loop thread, if there is a performance issue, you can optimize the discretionary
  3. [Recommended] Do not allow exceptions to be caught and then not handled in any way, if you don't want to handle it, throw it.
  4. The method may return null, the caller should do non-null judgment to prevent NPE problem.
  5. Avoid throwing RuntimeException directly, use business exceptions, such as BusinessException, ApplicatinException, DomainException.

1.7 Log specification

  1. [Recommended] Extended log file naming format for apps logName.time. logType: log type, for example, json means structured log, app means ordinary log, logName: log name.
  2. [Recommended] Separate the error log from the business log.
  3. [Recommended] The exception log must contain stack information and field parameters.
  4. [Mandatory] It is strictly forbidden to output a large number of invalid logs, such as in a big loop.

1.8 Note specification

  1. [Reference] Use the Javadoc specification for comments on classes, class attributes, and class methods, using the /**content**/ format and avoiding the // xxx approach.

  2. All abstract methods (including those in interfaces) must be annotated with Javadoc, indicating what the method does and what it accomplishes, in addition to return values, parameters, and exception descriptions.

 Note: Please include any implementation requirements for subclasses, or calling considerations.
  1. [Recommended] All enumerated type fields should have comments describing the purpose of each data item.

  2. [Recommended] While the code is modified, the comments should also be modified accordingly, especially the parameters, return values, exceptions, core logic and so on.

  3. [Ref] Be careful about commenting out code. Detail it above, rather than simply commenting it out. Delete if not useful.

 Note: There are two possibilities for the code to be commented out:
  1. This code logic will be restored later.
  2. It is not used permanently. In the former case, if there is no comment information, it is difficult to know the motivation for commenting. In the latter case, it is recommended to delete the code directly (the code repository keeps the history of the code).
  1. [Reference] for the requirements of the comments: First, to accurately respond to the design ideas and code logic; Second, to describe the business implications, so that other programmers can quickly understand the information behind the code. Completely no comments on the large sections of code for the reader is the same as a book, comments are for their own eyes, even after a long time, but also a clear understanding of the thinking at the time; comments are also for the successor to see, so that he or she can quickly take over his or her own work.

  2. 【Reference】 good naming, code structure is self explanatory, annotations strive to be concise and accurate, expression in place. Avoid one extreme of the annotations: too much and too indiscriminate annotations, the logic of the code once modified, modify the annotations is quite a burden.


// The counterexample put elephant into fridge
put(elephant, fridge).
The method name put, along with the two meaningful variable names elephant and fridge, already explains what it's doing, and the semantically clear code doesn't need additional comments.
  1. [Recommended] Clean up code snippets or configuration information that is no longer in use in a timely manner.

     Description: For garbage code or outdated configuration, resolutely clean up to avoid excessive program bloat and code redundancy.
     Positive Example: For code snippets that are temporarily commented out and may be resumed for subsequent use, above the commented code, it is standardized to specify the use of three slashes (///) to explain the reason for commenting out the code.
    

interface specification

  1. Mandatory] Rest interface return value must be BaseResult object and its subclasses object, encapsulated error code, error description, isSuccess, data information. data put business data. Business error code defined by themselves, it is recommended to prioritize the use of English, to avoid the use of generic error code, generic error code reference ExceptionEnum.

For example {code: "0",msg: "operation successful",data:{XX}}.

  1. [Recommended] The Rest interface must indicate the content_type of the request. e.g. content_type=applicaton/json

  2. [Mandatory] Interface providers must consider idempotency to prevent duplicate calls from causing serious business disasters.

  3. [Mandatory] The query interface needs to be paged back if the amount of data is too much.

  4. [Recommended] The interface must indicate the type of field, its length, whether it is required or not, and the text description must be accurate, counter-example: person:Person.

  5. Positive example: person:person code.

  6. [Recommended] Rest interface return values need to take into account the actual functionality, security and performance requirements, refined on-demand return business data.

    1. For example, the mobile interface needs to consider performance issues to avoid returning invalid fields; for the redundant field scenarios returned by the mobile interface of the middle station service, it needs to be encapsulated and processed by the business application before returning to the mobile terminal.

      PC interface return value requirements Mobile interface return value requirements
      China Central Office (CCO) service Just meet the actual function and safety It is sufficient to meet the actual functionality and security. Performance requirements need to be encapsulated by the business application.
      business application Just meet the actual function and safety In addition to meeting actual functionality and security requirements, consider performance and avoid returning invalid fields
  7. The Feign Api provider prohibits the introduction of AutoConfiguration and other startup-affecting configuration classes in the jar for downstream users.

Database specification

1. Norms related to table construction

  1. Library name, table name, field name, use lowercase and underscore _Segmentation
  2. Library name, table name, field name, no more than 12 characters. 64 characters are supported by default.
  3. Library name, table name, field name, see the name, it is recommended to use a noun rather than a verb.
  4. Uses InnoDB storage engine. Supports; transactions, locking, high concurrency Good performance.
  5. We recommend using utf8mb4 to save emoji.
  6. Number of fields in a single table, no more than 40 recommended

2. Field-related specifications

  1. Set length is not shown in integer definitions, e.g. use INT instead of INT(4)
  2. Storing precision floating-point numbers, using DECIMAL instead of FLOAT and DOUBLE.
  3. All fields with Comment description
  4. All fields should be defined as NOT NULL
  5. Over 2038, stored in DATETIME
  6. Short data type 0~80 Optional TINYINT storage
  7. UUID has a globally unique uniform field attribute and is suitable for synchronized ES use.
  8. IPV4 with unsigned INT storage
  9. IPV6, stored in VARBINARY
  10. JSON MySql New Features
  11. update_time sets the on update update property

3. Indexing-related norms

  1. Require a self-incrementing ID as the primary key, don't use the more random order_id as the primary key, it will lead to innodb internal page splitting and lots of random I/O, performance degradation.

  2. It is recommended to control the number of single table indexes to less than 5, and the number of single index fields should not exceed 5. Note: There is already an idx(a, b) index and an idx(a) index, you can delete idx(a), which wastes space and reduces update and write performance. * In a single index, the length of each index record can not exceed 64KB.

  3. Utilize the cover index to perform query operations and avoid table returns. Also when building a combined index, the highest differentiation is on the far left.

  4. select(count(distinct(field)))/count(id) = 1 It is more suitable to build indexes on fields with low distinctiveness. It makes little sense to build separate indexes on fields with low differentiation, such as type and status, reducing update and write performance.

  5. Prevents implicit conversions caused by different fields, which can lead to index failure.

  6. Fields that are updated frequently should not be indexed.

4. Use of relevant norms

  1. The amount of data in a single table does not exceed 5 million rows, and the size of the ibc file does not exceed 2G.

  2. Horizontal sub-tables with fetch mode, logs, report classes, can use date

  3. Number of tables in a single instance is less than 500

  4. Before alter table, first determine the table data volume, for more than 100W rows of records for the table alter table, must be executed in the business peak period. Because alter table will generate a table lock, during which all writes to the table are blocked.

  5. SELECT statements must specify specific field names and are prohibited from being written as“*”select * Will not need to read the data from MySQL also read out, causing pressure on the network card, data table fields once updated, but the model layer did not have time to update, the system will report an error!

  6. The insert statement specifies a specific field name, not `insert into t1 values(...)`.

  7. ``insert into...values(XX),(XX),(XX)... ` Here the XX values should not exceed 5000, too many values will cause the master-slave synchronization delay to become large.

  8. union all cap (a poem)union, do not exceed 5 clauses, if there is no need for de-duplication, use union all performance is better.

  9. The list of in values is limited to 500, for exampleselect… where userid in(….500less than…), which reduces the underlying scanning and reduces the pressure on the database.

  10. Except for static or small tables (less than 100 rows), DML statements must have a where condition and use index lookups where possible

  11. Production environments prohibit the use of hints, such as sql_no_cache, force index, ignore key, straight join, and so on. Trust the MySQL optimizer. hints are used to force SQL to execute according to a certain execution plan, but as the amount of data changes we can't guarantee that our initial prediction was correct.

  12. In the where condition, the types of the left and right fields of the equal sign must be the same, otherwise it will result in an implicit type conversion, which may lead to the inability to use indexes

  13. It is strongly not recommended to perform full table scans on large tables in production databases, and the amount of query data should not exceed 25% of the number of rows in the table, or it may lead to the inability to use indexes

  14. The where clause prohibits the use of only fully fuzzy LIKE conditions for lookups, such as like '%abc%', there must be other equivalent or range query conditions, otherwise it may result in the index not being able to be used

  15. Do not use functions or expressions for indexed columns, such aswhere length(name)=10 maybewhere user_id+2=1002Otherwise, the index may not be used

  16. Reducing the use of or statements or can potentially be optimized by mysq l to support indexes, but it also costs mysql cpu performance. The or statement can be optimized as a union and then indexed on each where condition. For examplewhere a=1 or b=2 optimize towhere a=1… union …where b=2, key(a),key(b) Some scenarios can also be optimized forin

  17. Pagination query, when the limit starting point is high, you can first use the filter conditions for filtering. For exampleselect a,b,c from t1 limit 10000,20; optimized forselect a,b,c from t1 where id>10000 limit 20;

  18. Field additions and deletions, index additions and deletions of the same table are merged into a single DDL statement to improve execution efficiency and reduce interaction with the database.

  19. replace into cap (a poem)insert on duplicate key update Execution in concurrent environments may produce deadlocks (the latter in version 5.6 may not report errors, but the data may produce problems), the need to catch exceptions, do transaction rollback, specific lock conflicts can be concerned about thenext key lockrespond in singinginsert intention lock

  20. TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources, but TRUNCATE has no transactions and does not trigger a trigger, which can cause accidents, so it is not recommended to use this statement in development code. Note: TRUNCATE TABLE is functionally the same as DELETE without the WHERE clause.

safety norm

interface security

  1. [Compulsory]Increased flow limiting and intranet access protection for interfaces involving large volumes of sensitive data
  2. [Compulsory]Increased intranet access protection for interfaces involving small volumes of sensitive data
  3. [Compulsory]Interface permissions must be added to all data that should not be made public

code security

  1. Mandatory] Newly added jars can only be used after security testing and evaluation by the technical center group.
  2. [Mandatory] Sensitive fields are not allowed to be stored in plaintext and need to be encrypted using a unified tool class.
  3. [Mandatory] Don't use ${} in mybatis when you can use #{}, #{} prevents SQL injection. Prohibit SQL splicing of unsafe parameters.

Password security

  1. [Mandatory] All business systems in use (including test environments) must have a password that consists of four combinations of uppercase letters + lowercase letters + numbers + special characters, with no less than 8 characters.

Specifications for writing technical documentation

  1. The core elements needed for the design document are Business Architecture , Application Architecture, Domain Model (Data Architecture), Technical Architecture, .
  2. Business architecture depicts the business processes and functions of the system
  3. Application architecture depicts relationships between systems
  4. Data architecture refers to the relationships of the domain model
  5. Technical architecture depicts the system implementation, we are more unified technical architecture, can be omitted

Java development programming military rules

I. Prohibit querying the database in the loop, try to query once outside the loop

  • clarification

A large part of the system performance bottleneck is directed to the database, and querying the database in a loop is very resource intensive.

  • case (law)

When displaying a small amount of tree-structured data, the data is assembled after querying the data within a loop. This causes the server to go down frequently just in the test environment.

Using the #compare method to call the database query interface resulted in very low performance on the wire.

Second, prohibit the use of redis such cache as a database

  • clarification

Caching is not fully compliant with the ACID principle of transactional characteristics, and there is a higher risk of data being unavailable.

  • case (law)

Membership data is stored directly into the redis cache, which also has a large amount of data and often loses data.

Prohibit the creation of new threads in the loop, try to use the thread pool

IV. Deadly cycles must have an exit mechanism

  • clarification

It is desirable to have a sleep statement present in a dead loop, in addition to an exit mechanism.

  • case (law)

When the order synchronization application requested data from a third-party platform, the platform side did not have an end-of-page flag, and at the same time, there was no exit mechanism in the code that directly led to an exception in order synchronization for that platform.

V. Shared variables must be considered thread-safe

  • clarification

Avoid using shared variables as much as possible; thread-safety must be considered when it cannot be avoided.

  • case (law)

In the WeChat sweepstakes feature, the winner is the same one every time due to a modification operation on a shared variable, and the logic behind it fetches dirty data.

VI. Floating point calculations must use BigDecimal

  • clarification

If you need to be precise, you have to use a String to create a BigDecimal.

VII. Batch operation must be considered reasonable grouping

  • clarification

Large amounts of data must be operated in batches, and batch operations must be grouped to avoid a single operation taking too long and leading to chain reactions.

  • case (law)

The order history migration data is grouped in 5000, resulting in the database deletion operation not going to the index. It is recommended that the number of groupings be between 100 and 500.

VIII. Prohibition of single-point deployment

  • clarification

Adding a server deployment reduces the risk of service unavailability by 50%.

IX. Prohibit full table scanning without current limiting for large tables

  • clarification

Full table scanning is already a drain on database resources, and frequent processing of requests without flow limiting adds to the problem.

  • case (law)

The export of after-sales issue tracking list, the time index did not control the range, resulting in a full table scan. The export data interface does not have a flow restriction to increase the consumption of service resources.

X. Read-write separation architecture, must consider reading expired data

  • clarification

Read-write separation suffers from latency problems when business data updates are written and then reads are reproduced, resulting in dirty data being read.

  • case (law)

A. On Double Eleven, when read-write separation is enabled, there is a delay in master-slave synchronization, which causes business events to be sent repeatedly due to reading historical dirty data.

B. The Membership Points service creates data that is immediately queried by other service applications, which results in empty data being queried.

XI. There are external calls within the transaction, and external instability and performance issues must be considered

  • clarification

Transactions themselves are very resource-intensive and highly prone to timeout problems, and it is important to avoid reintroducing external instability.

  • case (law)

Personal center services, remote querying of Beauty Sharing Officer's points within a transaction leads to very low performance. External interface calls require a timeout and maximum wait time to be set.

XII. Interface providers and Xxljob timed tasks must consider idempotence to prevent repeated calls leading to serious business disasters.

  • clarification

According to Murphy's Law, duplicate calls to interfaces are an inevitable online problem.

  • case (law)

Order payment interface, power and other logic is not rigorous resulting in duplicate payment problems. apollo report center due to xxljob a second repeated scheduling tasks, resulting in duplication of statistical data, seriously affecting the management's decision-making judgment.

XIII. Resource operations (IO, etc.) not released after being prohibited

XIV. the default propagation property of a nested transaction is. if you need to open a new transaction. you must manually set the transaction propagation property to Propagation.REQUIRES_NEW. try not to use nested transactions.

  • clarification

When using transaction annotations or programmatic transactions, you need to consider the default transaction propagation properties and decide whether to merge into the same transaction or open a new transaction as needed.

  • case (law)

OMS asynchronous operation tasks, when calling the third-party interface, modify the status to Acknowledged status, you need to submit the transaction update first, and then the subsequent logical operation needs to be modified to Acknowledged if it succeeds, or Pending Audit if it fails. When the third-party interface does not return a clear success or failure, the status should remain unchanged as Acknowledged. If you don't open a new transaction before calling the interface, it will lead to incorrect data to be rolled back later.

XV, override the object's equals () method must also override the hashCode () method

  • clarification

equals and hashCode method is the object in the hash container to work efficiently based on the correct override of these two methods in order to ensure the correctness of the hash container to find the object , while a good hashCode method can significantly improve the efficiency of the hash container .

Prohibit thread synchronization locks in loops containing transactions.

  • clarification

The upper level of the loop contains transactions, and using synchronized locks can cause MySQL transaction locks and JVM synchronized locks to wait for each other for deadlock issues.

  • case (law)
@Transactional(rollbackFor = )
public void storeData(List<Order> orderList) {
    /**order_id = {1,2,3}
    order_id = {1,2,3}
    Thread A enters the next loop after updating the order_id to 1. The transaction lock has not been released and the synchronization lock needs to be reacquired.
    Meanwhile, thread B has acquired the synchronization lock and needs to update the transaction operation of order_id=1. The result is that thread A waits for thread B to hold the
    JVM synchronization lock, and thread B waits for the transaction lock held by thread A. The result is that thread A waits for the transaction lock held by thread A.
    */
    for(Order order : orderList) {
        synchronized (LOCK) {
            updateOrderId(order);
        }
    }
}

Seventeen, the use of thread pools, you must set a reasonable size, prohibit unrestricted dynamic batch creation of threads

  • clarification

Unrestricted batch creation of threads can grab a lot of system resources, triggering a chain of exceptions such as OOM, and ultimately leading to downtime

  • case (law)

The code to create a thread pool with new MapReduce<>(xxx) was placed in the API interface implementation method without any other restrictions, resulting in OOM downtime, which triggered exceptions such as Redis connection timeout, Kafka duplicate consumption, and so on.

Eighteen, all public code (such as api packages, common tools) or public services (center services, business applications own services) changes, must be considered backward compatibility

  • Description -

Changes to public code on which multiple system projects depend need to be considered in the context of compatibility with historical logic, unless it can be confirmed that all users are able to accept the impact of the functionality change.

  • case (law)

The developer of project A modified the logic in the public jar package (the modification requires opening a new configuration to be consistent with the original logic), while deploying the jar package for testing, the new configuration is only operated in the test environment. Project B, which relies on the public jar package, then releases the version online, but does not configure it (and does not know that there is such a configuration), resulting in online accidents.

XIX. Prohibit the setting of character sets and sorting rules when creating a new table or adding or modifying table fields.

  • Description -

Character set and sorting rules need to consume huge resources for later modification, which affects the stability of the business. In order to maintain the consistency of the character set and sorting rules of schema-table-table fields, it is prohibited to set the character set and sorting rules when you create a new table or add or modify a table field.

  • case (law)

A project of a table field set the character set and sorting rules, resulting in inconsistent with the sorting rules of the table-schema, in the joint query of this table as a correlation field, reported that the correlation field sorting rules are inconsistent with the error, can not carry out correlation query, you can only modify it, if it is a large table to modify it will be very time-consuming, taking up a lot of io will affect the business.

XX. The use of TEXT/BLOD fields when creating a new table or adding a modified table field requires an assessment of necessity.

  • Description -

TEXT/BLOD large fields will produce a disk temporary table, and can not use the full-text index, the cost of various operations are very high, it is best not to use in the business, if you really want to use, but also to be independent of a table dedicated to storage, shall not be used with the business table.

  • case (law)

A project in the early stages of a table using a TEXT storage json large fields, resulting in this table occupies more than 600G of space, in which a large field occupies 90% of the table space, the subsequent query, migration, defragmentation are very resource-consuming.