Ali java code standards

Naming conventions

  1. Camel class life MarcoPolo
  2. Method name localValue
  3. Constant capitalized words, between words _ segmentation, semantic clear MAX _ STOCK _ COUNT
  4. Abstract class Abstract / Base start, end with exception class Exception, the end of test Test
  5. boolean types, variables do not begin with is
  6. Unified package name of English words in the singular, not use abbreviations
  7. Interfaces without modification, public do not add
  8. Use ending -able to describe the ability of the interface

Code format

  1. Between spaces, if / for / while / switch / do and other reserved words and brackets does not appear between the left parenthesis / right and characters must be spaces
  2. Two items, ternary operator needs both sides of a space
  3. The second row relative to the first row indented four spaces, others not indented
  4. To pass multiple parameters separated by spaces
  5. Insertion logic between different service or a different semantics blank line. Without inserting a blank line between the same business logic and semantics

OOP Statute

  1. Access class static methods without an object reference class, the direct use of the class name to access it.

  2. Outdated interfaces, @ Deprecated annotation

  3. You can not use outdated class or method

  4. Constant values ​​or determine object to call equals, "test" .equals (object);

  5. Comparison between the wrapper class object value, all using the equals method comparison
    for Integer var =?
    Assignment in the range -128 to 127, Integer object is IntegerCache. Cache generation, will reuse existing object, Integer within this range == value can be used directly for determination, but all data outside this range, the heap will have, and will not reuse an existing object, which is a pit,
    recommended is determined using the equals method.

  6. POJO class attributes must be packed data type, RPC parameter and return value data types must be packaged

  7. All local variables using basic data types.

  8. Defining DO / DTO / VO POJO class, etc., do not set any attribute default values

  9. POJO class must write toString method.

  10. Connection string using the StringBuilder append extension method.

Collection process

  1. As long as rewriting equals, it is necessary to rewrite hashCode. If the custom objects as Map keys, you must rewrite the hashCode and equals.
  2. subList result ArrayList of ArrayList can not turn into a strong, otherwise it will throw a ClassCastException, namely java. util. RandomAccessSubList can not be cast to java. util. ArrayList.
  3. Arrays. AsList () array into a set of time, which can not be used to modify a set of related methods, it add / remove / clear method throws an UnsupportedOperationException. asList return object class is an internal Arrays, and does not implement the modification method set.
  4. Generic wildcard <? Extends T> to receive the data returned, the wording of this generic collections can not use the add method, and <? Super T> not use the get method, as you call assignment error-prone interfaces. First, frequently read out the contents, suitable for use <? Extends T>. Second, often inserted inside, suitable for use <? Super T>.
  5. Do not remove the elements in the foreach loop in / add operations. remove elements, use Iterator way, if concurrent operations, the need for Iterator object locking.
  6. When a set of initialization, the initial value of a specified set size. Description: HashMap using HashMap (int initialCapacity) initialization,
    Example n: initialCapacity = (the number of elements need to store / load factor) + 1. Note that the load factor (i.e. loaderfactor) defaults to 0.75, if the initial value is temporarily unable to determine the size, set to 16 (i.e., default value).
  7. Use entrySet traverse Map collection of classes KV, rather than keySet way to traverse. The entrySet just traversed a key and value are put into the entry in higher efficiency.

Collections | Key | Value | Super | Description
--- | ------ | ------ | ----- | ------ | ---
Hashtable | does not permit null | does not permit null | Dictionary | thread-safe
ConcurrentHashMap | does not permit null | does not permit null | AbstractMap | lock segmentation techniques (JDK8: CAS)
TreeMap | does not permit null | allowed to be null | AbstractMap | thread safe
HashMap | allowed to be null | allowed to be null | unsafe thread | AbstractMap

ConcurrentHashMap store null throws NPE exception value.

Concurrent processing

  1. Thread resources must be provided by the thread pool is not allowed to explicitly create their own threads in the application.
  2. Executors thread pool are not allowed to create, but by ThreadPoolExecutor way, this approach allows the students to write more explicit operating rules thread pool, to avoid the risk of resource depletion.
  3. SimpleDateFormat is not thread-safe class, usually not defined as a static variable, if defined as static, must be locked, or use DateUtils tools.
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@ Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};

jdk8 DateTimeFormatter may be used instead of simpleDateFormat

  1. When the multi-threaded parallel processing timing task, when Timer running multiple TimeTask, as long as one does not catch
    exceptions thrown, other tasks will automatically terminate, use ScheduledExecutorService is not the problem.

  2. Avoid Random instance is using multiple threads, although sharing the instance is thread-safe, but due to competing for the same
    seed results in performance degradation. After JDK 7, can be used directly API ThreadLocalRandom.

  3. In concurrent scenario, double-checked by a lock (double - checked locking) to achieve optimal delay initialization
    problem hidden (refer The "Double - Checked Locking is Broken " Declaration), the recommended solution
    must relatively simple in embodiment (suitable for JDK 5 and above), the target property declared as volatile type.

  4. volatile memory to solve the multi-threaded invisible problem. For a write once read many, synchronization problems can be solved variables,
    but if you write, the same can not solve thread safety issues. If yes count ++ operation, implemented using the following categories:
    . Of AtomicInteger of AtomicInteger new new COUNT = (); COUNT addAndGet (. 1); if JDK 8, pushing
    recommended to use LongAdder object AtomicLong performance better than (reduction optimistic locking retry the number of times).

  5. HashMap when capacity is insufficient due to high concurrency carried resize dead links may occur, resulting in CPU surge in
    use of other data structures or locking the development process to avoid this risk.

Control statements

  1. When the abnormal expression of the branch, less if-else, this approach can be rewritten as
if (condition) {
...
return obj;
}
  1. The return value method can be null, not forced to return empty set, or an empty object, etc., you must add a comment to fully
    explain under what circumstances would return a null value. The caller needs to be null judge to prevent the NPE problem.

  2. When defining distinction unchecked / checked exceptions, avoid direct throw new RuntimeException (),
    but not allowed to throw Exception or Throwable, you should use custom business meaning there are exceptions.

  3. Applications can not directly use the system log (Log 4 j, Logback) of the API, but rather rely on the use logging framework
    SLF 4 J in the API, logging framework used facade patterns, facilitate the maintenance and unified logs approach each class.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Abc.class);
  1. Print Log avoid duplication, waste of disk space, be sure to log 4 j. Xml setting additivity = false.
    Positive Example:
    <Logger name = "com.taobao.dubbo.config" = the additivity "to false">

unit test

  1. Unit testing should be performed fully automatic and non-interactive. Testing framework is usually performed on a regular basis, the implementation
    process must be fully automated meaningful. The output test requires manual inspection is not a good unit test. Unit senses
    the test are not allowed to use System.out to verify human flesh, must assert to verify.

Mysql

  1. Expression is the concept of a field or not, must be used in the embodiment is _ xxx name, the data type is unsigned tinyint (1 is represented, 0 for No)
  2. Primary key index named pk_ field name; a unique index named uk _ field names; ordinary index name was idx _ field names.
  3. Decimal type is decimal, prohibit the use of float and double.
  4. Table must have three fields: id, gmt _ create, gmt _ modified
  5. Named the best table is to add "_ the role of the business name of the table."
  6. More than three tables prohibit join. Need to join the field, data types must be absolutely consistent; multi-table associated with the query,
    ensure the field is associated with the need for the index.
  7. Search page is strictly prohibited left vague or fuzzy whole, if necessary, please take the search engine to solve. The index file has a B - Tree of the most left-prefix matching characteristics, if the left value is not determined, you can not use this index.
  8. Do not use the count (column name) or count (constant) instead of count (*), count (* ) is defined SQL 92
    Syntax number of standard statistical line, nothing to do with the database, nothing to do with NULL and non-NULL. count (*) counts the line value is NULL, and count (column name) does not count rows in this column is NULL values.
  9. count (distinct col) calculates the number of columns is not repeated in the rows other than NULL, attention COUNT (DISTINCT
    COL. 1, COL 2) If a NULL is full, even if the other columns have different values, but also returns to zero.
  10. When the value of a column are all NULL, count (col) returns a value of 0, but the sum (col) returns a value
    to be noted problems NPE NULL, so the use of sum (). You may be used in the following manner to avoid the problem of sum NPE: SELECT IF (ISNULL (SUM ( g)), 0, SUM (g)) FROM table;
  11. Using the ISNULL () to determine whether a NULL value. A direct comparison with any NULL values ​​are NULL.
  12. When writing paging query logic in code, if the count is zero should be returned directly to avoid the implementation of pagination statement back.
  13. Not use foreign key with a cascade, all foreign key concepts that must be addressed in the application layer.

server

  1. Highly concurrent server recommended time_wait timeout turn down the TCP protocol. Operating system default is 240 seconds will be closed in time_wait link, under high concurrency server in time_wait because too many connections, the new connection can not be established, it needs to wait for a small value.

Modify default values ​​by changing the /etc/sysctl.conf on linux server

net.ipv4.tcp_fin_timeout = 30
  1. Handles maximum file transfer large server support. Mainstream operating system TCP / UDP connection using the same connection and file management, a connection corresponds to a fd.
    Linux default number is 1024. The number of concurrent fd over the General Assembly led to "open too many files" error.

  2. To the JVM settings -XX: + HeapDumpOnOutOfMemoryError parameters, let JVM hit OOM output Dump

  3. The JVM line Xms Xmx initial heap size and storage capacity as the maximum heap size, to avoid putting pressure on the stack to adjust GC

  4. Internal server redirects the use of forward, external redirect URL using assembly tool to generate, maintain or bring URL inconsistencies.

Second party library dependencies

  1. Do not rely on snapshot version of the online application, it does not rely on a guarantee issued by idempotency.

  2. New or upgraded second party library, keeping the other jar package in addition to Function Point arbitration result unchanged. If there is a change, you must explicitly assess and verify, recommendations dependency: resolve information before and after contrast, if the result of the arbitration completely inconsistent, through dependency: tree to find points of difference, be excluded excludes jar package.

  3. Library can define two side enumerated type, enumerated type parameter may be used, but the interface does not allow the return value enumerated type, or enumeration type comprising pojo

  4. When relies on a two-party library, you must define a unified version, the version number to avoid inconsistencies.

Stratified

In Dao layer, the catch can not be fine-grained abnormality, so use catch (Exception e) embodiment, and throw new DAOException (e) printing is not performed.

In manager / service layer to capture and print to the log, service log output to disk layer, web layer jump to the friendly interface.

ORM mapping

  1. Never use table query * as a query field list, the fields that need to be stated.
  2. pojo properties can not be added is, database fields must be added is_, you will need to be modified in mybatis code generator.
  3. sql.xml configuration parameters # {}, {} $ do not use such a manner prone to SQL injection
  4. Do not allow direct output to take HashMap and HashTable as a query result set.
  5. Do not abuse the transaction, the transaction affect QPS database using a transaction rollback place to consider all aspects.

SQL statements

  1. count (distinct col) calculate the column is not repeated the rows other than NULL, note count (distinct col1, col2) wherein if a whole is null, even with different values ​​of the other row also returns 0.
  2. When a whole column value is null, count (col) returns a value of 0, sum (col) returns a value of NULL, therefore Sum (col) NPE should pay attention to the problem. Can use
select if(isnull(sum(g)),0,sum(g)) from table;
  1. Using the ISNULL () to determine whether the value is NULL, NULL value and any value comparison are NULL value.
  2. Prohibit the use of stored procedures, stored procedures, difficult to debug and extend, and no portability.
  3. When the revised data, delete, and modify records, first select, to avoid accidentally deleted, confirmation to avoid accidental deletion.
  4. in operation can be avoided, avoid, it can not be avoided to estimate the number in the back of the set, the control within 1000.
  5. If there is a need of globalization, all the characters stored in utf-8 for storage, while paying attention
select length("轻松工作");返回12
select character_length("轻松工作"); 返回4

Expression with utfmb4 storage for storage, and it is noted that the difference between the utf-8.

8. not recommended truncate

Index Statute

  1. Field has a unique operational characteristic, even if the combination of a plurality of fields, a unique index must be constructed.
  2. Varchar created on the index, you must specify the length of the index, there is no need to index the whole field, you can determine the length of an index based on the actual text of discrimination.
count(distinct left(列名,索引长度))/count(*)
  1. If there is order by the scene, note the use of the orderliness of the index. The final order by the field is part of the composite index, and the index on a combination of final order, to avoid the appearance file_sort affect query performance.
索引 a_b_c      where a = ? and b = ? order by c 

When the index has a range of search, the ordering index can not be used, where a> 10 order by b; index a_b not occur.

  1. Use the index to cover the query, to avoid the back to the table, to build the type of indexes: a primary key index, the only index, the general index, while covering index is an effect of one kind of query, the results explain the use, extra columns will appear, using index

  2. Delays associated with the use of sub-query optimization or paged much worse scenario.

  3. SQL performance objectives, to reach at least the level range, ref are required level, if may be preferable consts
    consts single table can have at most one matching row, the optimization phase can read the data
    ref refers to the use ordinary index
    range search range for index

  4. When building composite index, the highest distinction of the left-most, if where a =? And b =? A column almost close to unique values, then you only need a single index can be built idx_a.
    And the presence of non-equal sign equal sign hybrid judgment conditions, when you create the index, the column pre-condition of the equal sign.
    where a>? and b =? a high degree of differentiation even need b on top index.

  5. Implicit prevent conversion of different types of fields caused, resulting in failure index.

  6. To avoid creating an index rather the lack of abuse do not think you need to create a query index, Ningquewulan do not think the index will consume space and slow down the speed of updates and additions.
    Boycott unique index, the only index needs to think first and then check the plug settlement in the application layer.

  7. varchar variable length strings, not pre-allocated storage space, a length not more than 5000, if the memory length is greater than this value, defined as the field type text, separate out a table, with the corresponding primary key, to avoid affecting other fields efficiency index.

  8. Single-row table data over five million or single-row table capacity of more than 2GB, it is recommended sub-library sub-table.

  9. Suitable character storage length, not only save table space databases, saving the index storage, more importantly, to enhance the retrieval speed.

Security Statute

  1. Personal pages must verify permissions.

  2. Sensitive user data ban on direct display, must desensitization, phone number hidden among four.

  3. sql user input parameters or parameter binding strictly prohibited metadata field value is defined, to prevent SQL injections, prohibiting access to the database SQL string concatenation.

  4. Incoming user request parameters have valid verification: 1.page size otherwise cause excessive overflow of memory 2. The order by malicious database query results in slow 4.SQL redirect any injected 3. 5. 6. deserialization injection regular input Denial of service source string ReDos

  5. Disable the output of user data without security filtering or improperly escaped to the HTML page.

  6. Forms, AJAX submission must perform CSRF security filtering.
    CSRF CSRF is a kind of common programming flaw, for the presence of CSRF vulnerabilities of the application site, an attacker can construct well in advance URL, as long as a victim user access, the background will make changes to the database without the user's knowledge.

  7. Unit test can be repeated, is not affected by the external environment, it is imperative SUT designed to inject, using DI frame of such a spring local injection to achieve during the test.

Exception Handling

  1. java class libraries defined in a class can be circumvented by RuntimeException checked in advance, and should not be treated by the catch, such IndexOutOfBoundsException, NullPointerException

  2. There try block into the transaction code, after the catch, the need to roll back the transaction, attention must manually roll back.

  3. Finally can not be used in the return, the return finally return block performing the method ends, and will not return in the try statement.

  4. The return value method can be null, not empty set and forced to return empty object, you must add a comment to explain the circumstances under which return empty

other

  1. In use regular expressions to learn to use precompiled, accelerate the speed of a regular match, when it is not being defined in the method body definition.

  2. volocity call POJO class properties when used as recommended value to the property name, template engine will automatically call in accordance with the Statute of Pojo getXxx (), if the basic data types are boolean calls isXxx (), if the Boolean wrapper object, call getXxx ( )Methods

  3. Background output must be added to the variable page! {Var} will be displayed on the page.

  4. Any data structure configuration and initialization, should specify the size of the data structure to avoid unlimited growth eat up memory.

  5. For the time being is commented out, the subsequent recovery code fragment might be used, uniform use to justify /// commented code.

Reproduced in: https: //www.jianshu.com/p/6a88cf7b18e8

Guess you like

Origin blog.csdn.net/weixin_34040079/article/details/91111112