Development specification interpretation

[Force] equals method of Object readily shorting pointer exception, should be used with a constant or a value determined object equals to call.

正例:"test".equals(object);

反例:object.equals("test");

Description: Recommended use java.util.Objects # equals (JDK7 introduced tools).

Object class equals source code under:

public  Boolean the equals (Object obj) {
     // comparison target point to the same memory address 
    return ( the this == obj); 
}

 Overridden equals source code under the String class:

public  Boolean the equals (Object anObject) {
    // compare the incoming call the originating object, the same object is an 
   IF ( the this == anObject) {
        return  to true ; 
   } 
   // determines whether the current incoming string type 
   IF (anObject the instanceof String ) { 
       string anotherString = (string) anObject;
        int n-= value.length;
       //   compare two objects string length 
       IF (n-== anotherString.value.length) {
            char V1 [] = value;
            char V2 [] =anotherString.value;
            int I = 0 ;
            // same if the length of the character array per a comparison 
           the while (N-- = 0! ) {
               IF (V1 [I] =! V2 [I])
               return  to false ; 
              I ++ ; 
            } 
            return  to true ; 
       } 
   } 
   // do not directly returns false / string to 
   return  to false ; 
}

The reason to avoid a null pointer, the null value of the object as a parameter, to determine if two are false, so direct returns false, do not report NPX exception.

Comparison between the value of [force] packaging all objects of the same type, all using the equals method to compare.

? Description: For assignment Integer var = -128 to 127 range, Integer object is generated IntegerCache.cache will reuse existing object, Integer values ​​within this range may be used directly for determination ==, but this interval All data outside, the heap will be produced, not reusing existing object, which is a pit, is determined using the equals method recommended. 

Basic data on the type of pack data type using the following criteria: 

1)] [all mandatory attributes must POJO class packed data type. 

2) [RPC] forcibly return value and parameters must be packed data type. 

3) [Recommended] all local variables using the basic data types. 

Description: POJO class property is not the initial alert the user when needed, you must explicitly assign their own, NPE any questions or warehousing inspection, by the user to be guaranteed. Positive examples: database results may be null, because the automatic unpacking, with basic data types have to receive NPE risk. Counterexample: the total turnover of ups and downs such as display cases, that is plus or minus x%, x is the basic data types, called RPC service when the call is unsuccessful, the returned value is the default page displayed as 0%, which is unreasonable, It should be displayed as the scribe line. So Packaging data type null value can represent additional information, such as: remote call fails, quit unexpectedly.

[Recommended] can be declared final class, member variables, methods, and local variables, the following final keyword:

1) does not allow inherited class, such as: String class.

2) not allowed to modify the domain object references.

3) does not allow the method to be rewritten as: setter method POJO class.
4) Local variables are not allowed to run in the process of re-assignment.

5) Avoid repeated use of a context variable, using the final description may redefine a variable force to facilitate better reconstruction.

[Recommended] caution Object clone method to copy objects.

Description: clone method is the default object shallow copy, are to achieve the depth of a deep copy clone traversing the copy-implemented method needs to be rewritten domain objects.

[Recommended] class members and strict access control methods:

1) If not directly create an external objects through new, then the constructor must be private.

2) tools have allowed public or default constructor.

3) class of non-static member variables and shared with subclasses, must be protected.

4) class non-static member variables and only use this type must be private.

5) If the class static member variables in this class use only, must be private.

6) If the static member variables to consider whether the final.

Internal 7) class method only for class members to call, must be private.

8) class member method only public inheritance class, then the limit is protected. Description: Any classes, methods, parameters, variables, and control access range. Overly broad scope of access, is not conducive to the decoupling module. Thoughts: If it is a private method to remove to delete, but a public method of service members or member variables, delete it, may not take points palms sweat it? Variables like their own children, as much as possible in their own sight, variable scope is too large, unrestricted everywhere, then you would worry. 

[Mandatory] hashCode and equals with regard to the processing of the following rules:

1) As long as rewriting equals, it is necessary to rewrite hashCode.

2) are not stored because the Set duplicate objects, is determined by their hashCode and equals, so the object is stored Set must override these two methods.

3) If the custom objects as Map keys, you must rewrite the hashCode and equals. Description: String override hashCode and equals methods, so we can be very happy to use a String object to use as a key. 

set

[Mandatory] subList results 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.
Description: subList returns the internal ArrayList class SubList, but not a view ArrayList of ArrayList, all operations for SubList sub-list will eventually be reflected in the original list.

。。。

[Mandatory] in subList scene, pay attention to the height of the original collection of elements to add or remove, will lead to traverse the sub-lists, add, delete produce ConcurrentModificationException exception.

。。。

[Use] set force transfer array, must be set toArray (T [] array), is passed in exactly the same type of array size is list.size ().

Description: toArray parameterized using a method, when the reference array allocated a large space is not enough, the internal toArray method reallocate memory space, and returns the new address of the array; if the number of array elements is greater than is actually required, the subscript [list.size ()] of the array element is set to null, the other array elements holding the original value, so the same method is preferable to set the number of parameters to define the size of the 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);
counterexample: no problems directly toArray reference method, this method can only return value Object [] class, if other types of arrays turn strongly ClassCastException error occurs.

[Force] using tools 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.

Description: asList returns the class object is an internal Arrays, and does not implement the modification method set. Arrays.asList embodies the adapter mode, only conversion interface, back-end data remains array.
String [] str = new String [ ] { "you", "wu"};

List list = Arrays.asList(str);

The first case: list.add ( "yangguanbao"); runtime exception.

The second case: str [0] = "gujin"; then list.get (0) will also be modified.

[Mandatory] generic wildcard <? Extends T> to receive the data returned, the wording of this generic collections can not use the add method, and <? Super T> get method can not be used as an interface call assignment when error-prone.

Description: Extension talk about PECS (Producer Extends Consumer Super) principles: first, frequently read out the content, suitable for use <extends T?>. Second, often inserted inside, suitable for use <? Super T>. 

....

[] Do not force the elements remove / add operations in the foreach loop. remove elements, use Iterator way, if concurrent operations, the need for Iterator object locking.

When [Recommended] collection initialization, the initial value of a specified set size. Description: HashMap using HashMap (int initialCapacity) initialization.

Positive Example: initialCapacity = (the number of elements need to store / load factor) + 1. Note that the load factor (i.e., loader factor) 0.75 default, if the initial value is temporarily unable to determine the size, set to 16 (i.e., default value).

Counter-example: HashMap 1024 elements need to be placed, because there is no capacity to set the initial size, with elements increasing the capacity of seven were forced to expand, resize need to rebuild the hash table, seriously affect performance.

 

Multithreading

[Mandatory] thread resources must be provided by the thread pool, do not allow yourself to explicitly create threads in the application.

Description: The benefits of using the thread pool is to reduce the overhead in creating and destroying threads consumed time and system resources, to solve the problem of insufficient resources. If you do not use the thread pool, it may cause the system to create a large number of similar threads lead consumed or memory problem "excessive handover".

[Mandatory] thread pool Executors 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.

Description: Executors malpractice thread pool objects returned as follows:

1) FixedThreadPool and SingleThreadPool: request queue length allowed Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM.

2) CachedThreadPool and ScheduledThreadPool: allow the number of threads to create Integer.MAX_VALUE, may create a large number of threads, resulting OOM.

 

Mysql

[Mandatory] table names, field names must be lowercase letters or numbers, start with a number banned, prohibited only the middle two numbers appear underlined. Modify the cost of a large database field names, because they can not carry out a pre-release, so the field names need to be carefully considered.

Description: MySQL is not case sensitive in Windows, but by default in Linux is case sensitive. Therefore, the database names, table names, field names, do not allow any uppercase letter, to avoid any further complications.

正例:aliyun_admin,rdc_config,level3_name

反例:AliyunAdmin,rdcConfig,level_3_name 

[Mandatory] decimal type is decimal, prohibit the use of float and double.

Description: float and double when stored, there is a loss of accuracy problems are likely when comparing values, get incorrect results. If the stored data exceeds the range decimal range, it is recommended to split into separate data store and decimal integer.

[Force] If the length of a string is almost equal, the use of fixed-length string type char.
[Varchar] mandatory 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, an independent list, with the corresponding primary key, to avoid affecting other fields efficiency index.

[Recommended] single table rows over 5 million lines or single-table capacity of more than 2GB, it is recommended sub-library sub-table.

Note: If the amount of data expected after three years failed to reach this level, you do not sub-library sub-table when creating tables. 

[Mandatory] indexing on varchar fields, you must specify the length of the index, no need for indexing the whole field, you can determine the length of an index based on the actual text of discrimination.
Description: the length of the discrimination index is a contradiction, the general type of string data length of the index 20, the discrimination will be more than 90%, can count (distinct left (column name, index length)) / count (*) to determine the degree of differentiation.

[Mandatory] search page is strictly prohibited left vague or fuzzy whole, if necessary, please take the search engine to solve.

Explanation: The index file with the most left-prefix match the characteristics of the B-Tree, and if the value is left undetermined, it can not use this index.

[Recommended] 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.

Positive Example: where a = and b = order by c; index:?? A_b_c

Anti Example: index has a range of search, then the ordering index can not be used, such as: WHERE a> 10 ORDER BY b; a_b not sorted index.

 

 

server

[Recommended] time_wait recommend highly concurrent server timeout turn down the TCP protocol.

Description: The operating system's default 240 seconds, before the connection is closed time_wait state, at high concurrent access, server-side because of too many connections in time_wait may not be able to establish new connections, you need this small increase in server wait value.

Positive Example: On linux server to change the default value (s) by changing the /etc/sysctl.conf file: net.ipv4.tcp_fin_timeout = 30 2.

[Recommended] adjust the maximum number of file handles large supported by the server (File Descriptor, abbreviated as fd).

Description: mainstream operating system is designed to connect the TCP / UDP uses the same way to manage files, namely a connection corresponds to a fd. Mainstream linux server default maximum number supported by fd 1024, when a very large number of concurrent connections
easily occur because of lack of fd "open too many files" error, leading to a new connection can not be established. The recommended maximum number of handles linux server supports multiple increase (related to the amount of memory the server).

[Recommended] to the JVM environment parameters -XX: + HeapDumpOnOutOfMemoryError parameters, let JVM output dump information when confronted OOM scene. Description: OOM occurs there is a probability, even a gap of several months to a single case, in the heap of information is very helpful to solve the problem when an error occurs.


[Recommended] production environment on-line, JVM's Xms and Xmx set the same amount of memory capacity, avoid adjusting the pressure caused by heap size after GC.


[Reference] internal redirect server using forward; external redirect using the URL address to generate the assembly tools, otherwise it will bring URL maintenance inconsistencies and potential security risks.

 

 

--- Ali from the development of norms

Guess you like

Origin www.cnblogs.com/dingpeng9055/p/11382593.html