Ali Development Specification Final edition finishing (streamlining)

Source: Internet
Author: User
Tags map class naming convention wrapper
Java Development Specification naming "Spec"Class names use the Uppercamelcase style and must be in the Hump form, except for the following: (related naming of domain models) do/bo/dto/vo. Positive Example: Marcopolo/userdo/xmlservice/tcpudpdeal/tapromotion Counter Example: Macropolo/userdo/xmlservice/tcpudpdeal/tapromot Ion
"Spec"Method names, parameter names, member variables, and local variables are uniformly used in lowercamelcase style and must be in the Hump form. Positive example: Localvalue/gethttpmessage ()/Inputuserid
"Spec"Constant name all uppercase, the words are separated by an underscore, so that the semantic expression is complete and clear, not too long name.
"Spec"An abstract class name begins with an abstract or Base; The exception class name uses the Exception end; the test class is named with the name of the class it wants to test, ending with test. Enumeration class names are recommended with the enum suffix, the enumeration member names need to be all uppercase, and the words are separated by an underscore.
"Spec"POJO A Boolean-type variable in a class without the IS, or partial framework parsing can cause serialization errors.
"Spec"Each layer naming convention: A) Service/dao Layer Method naming protocol 1) Gets the method of a single object to prefix with get. 2 The method of obtaining multiple objects is prefixed with list (custom: Getxxxlist). 3 The method of obtaining the statistic value is prefixed with count. 4 the insertion method is prefixed with save (recommended) or insert. 5 The method of deletion is prefixed with remove (recommended) or delete. 6 The modified method is prefixed with update (or modify). (B) domain model naming convention 1) Data object: Xxxdo, XXX is the data table name. 2 Data Transmission object: Xxxdto, XXX is the name of the business domain. 3 Display object: Xxxvo, XXX General for Web page name. 4) POJO is a general designation of DO/DTO/BO/VO, which is forbidden to be named Xxxpojo.
Constants "Spec"No magic value (that is, undefined constants) is allowed to appear directly in your code. Anti-Example: String key = "Id # Taobao _" + TradeID cache. Put (key, value);
Format Specification "Style"Line is too long to wrap
"Style"Inserts a blank line between the execution statement group in the method body, the definition statement group of the variable, the different business logic, or the different semantics. No blank lines need to be inserted between the same business logic and semantics.
OOP Conventions "Efficiency"Avoid using a Class object reference to access static variables or static methods of this class, needlessly increase the compiler resolution costs, directly with the class name to access.
"Spec"All overridden methods must be annotated with @ Override.
"Spec"Externally exposed interface signatures, in principle, are not allowed to modify method signatures to avoid having an impact on interface callers. An interface is obsolete and must be @deprecated annotated with a clear indication of the new interface used or what the new service is.
"Spec"The Equals method of object is easy to throw empty pointer exceptions, you should use constants or determine the value of the object to call equals. Positive example: "Test". Equals (object); Anti-Example: Object.Equals ("test");
"Spec"A comparison of values between all the wrapper class objects of the same type, all using the Equals method. ( Note NULL pointerNote: for integer var =? Assignment between 128 and 127, the integer object is in Integercache. Cache generation, will reuse existing objects, this interval in the Integer value can directly use = = to judge, but all the data outside this interval will be generated on the heap, and will not reuse existing objects, this is a large pit, recommended use the Equals method to judge.
"Spec"The use criteria for basic data types and wrapper data types are as follows: 1 All POJO class attributes must use the wrapper data type. 2 The return value and parameters of the RPC method must use the wrapper data type. 3 All local variables "recommended" use basic data types.
"Coercion"When serializing a new property in a class, do not modify the Serialversionuid field to avoid deserialization failure, or modify the Serialversionuid value if the upgrade is completely incompatible to prevent deserialization clutter.
"Spec"The constructor method prohibits adding any business logic, and if there is initialization logic, place it in the Init method.
"Spec"When using an index to access an array that is obtained using the split method of String, there is a need to check for content after the last delimiter, otherwise there is a risk of throwing indexoutofboundsexception. Description: String str = "a,b,c,,"; string[] ary = Str.split (","); Expected to be greater than 3, the result is 3 System.out.println (ary.length);
"Spec"When a class has multiple constructor methods, or multiple methods with the same name, these methods should be placed together in order to facilitate reading.
"Style"The order of method definitions within the class is: public method or Protection method > Private Method > Getter/setter method.
"Efficiency"Final can improve the efficiency of program response, declared final case: 1 variables that do not need to be assigned a value, including class attributes, local variables. 2 The object parameter is previously added final, indicating that the reference is not allowed to be modified. 3 The class method determines that it is not allowed to be overridden. 4 Example: Final Boolean existed = (File.Open (fileName, "w")!= null) && (...) | | (...);
Collection Processing "Coercion"With respect to the handling of hashcode and equals, follow the following rules: 1 if you rewrite equals, you must rewrite the hashcode. 2 because set stores a distinct object, based on hashcode and equals, the set store object must override both methods. 3 If the custom object is the key of the Map, then the hashcode and equals must be rewritten.
"Coercion"Do not remove/add the element in the Foreach loop. remove element Use iterator method, if concurrent operation, need to lock iterator object. Counter example: list<string> a = new arraylist<string> (); A.add ("1"); A.add ("2"); for (String temp:a) {if ("1". Equals (temp)) {a.remove (temp);} Description: The results of the above code will certainly be unexpected, then try to replace "1" with "2", will be the same result. (java.util.ConcurrentModificationException) Positive example: iterator<string> it = A.iterator (); while (It.hasnext ()) {String temp = It.next (); if (delete element's condition) {It.remove ();}}
"Spec"When the collection is initialized, try to specify the collection initial value size. Description: ArrayList try to initialize using ArrayList (int initialcapacity).
"Spec"Use EntrySet to traverse the Map class collection KV instead of the keyset method. Description: Keyset is actually traversed 2 times, one is to iterator object, the other is to remove the key from the hashMap corresponding to the value. And EntrySet just iterate over the key and value are placed in the entry, more efficient. If it is JDK8, use the Map.foreach method. map<string, string> map = new hashmap<string, string> (); Map.put ("1", "@@"); Map.put ("2", "# #");
/** * JDK8 recommended the use of * * Map.foreach ((K, V)-> {System.out.println ("Key:" + K); System.out.println ("Value:" + V);});
/** * foreach is recommended to use the */for (map.entry<string, string> entry:map.entrySet ()) {System.out.println ("Key:" + entry.ge TKey ()); System.out.println ("Value:" + entry.getvalue ());}
/** * is not recommended to use */for (String Key:map.keySet ()) {System.out.println ("key:" + key); System.out.println ("Value:" + map.get (key));}
"Coercion"Note that the Map class collection k/v can store null values in the following table:
Collection Class Key Value Super Description
Hashtable NULL is not allowed NULL is not allowed Dictionary Thread Safety
Concurrenthashmap NULL is not allowed NULL is not allowed Abstractmap Segmented lock Technology
TreeMap NULL is not allowed Allow null Abstractmap Thread not secure
HashMap Allow null Allow null Abstractmap Thread not secure

Concurrent Processing "Spec"Getting a single Instance object requires thread safety, and the method also guarantees thread safety. Description: Resource-driven classes, tool classes, and single example factory classes all need attention.
"Spec"When creating threads or thread pools, specify a meaningful thread name to facilitate backtracking when errors occur. Positive example: public class Timertaskthread extends Thread {public timertaskthread () {super.setname ("Timertaskthread");}
"Spec"Thread resources must be provided through the thread pool, and it is not allowed to explicitly create threads in an application. Note: The benefit of using a thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources to address the problem of insufficient resources. If you do not use a thread pool, it is possible that the system creates a large number of similar threads that can result in memory depletion or "over switching" issues.
"Spec"Thread pool is not allowed to use executors to create, but through the way of threadpoolexecutor, this way so that students write more clear thread pool rules of operation, to avoid the risk of exhaustion of resources. Description: The disadvantages of the thread pool object returned by executors are as follows: 1 Fixedthreadpool and Singlethreadpool: The allowable queue length of the request is integer.max_value, which can accumulate a large number of requests, resulting in OOM. 2 Cachedthreadpool and Scheduledthreadpool: The number of created threads allowed is integer.max_value, and a large number of threads may be created, resulting in OOM.
"Efficiency"When concurrency is high, synchronous calls should consider the performance loss of the lock. Can use unlocked data structure, do not use lock, can lock block, do not lock the whole method body, can use object lock, do not use class lock.
"Coercion"When you lock multiple resources, database tables, and objects at the same time, you need to maintain a consistent lock order, or you may cause deadlocks. Note: Thread one need to table A, B, C, in turn, after all the lock can be updated operation, then the line Cheng lock order must also be a, B, C, or may appear deadlock.
"Spec"When you modify the same record concurrently, avoid the loss of updates, either by locking the application layer or by locking the cache, or by using the optimistic lock at the database level, using version as the update basis. Note: If the probability of each access violation is less than 20%, optimistic locks are recommended, otherwise pessimistic locks are used. The number of retries for an optimistic lock must not be less than 3 times.
"Spec"When a timer runs multiple timetask when a multithreaded parallel process is in use, as long as one of them does not catch the thrown exception, the other tasks are automatically terminated, and Scheduledexecutorservice is not the problem.
"Spec"HashMap when the capacity is not enough to resize due to high concurrency may appear dead chain, causing the CPU to soar, in the development process to avoid this risk.
Control Statements "Spec"Within a switch block, each case is terminated either by Break/return, or by commenting on which case the program will continue to execute; within a switch block, you must include a default statement and put it at the end, even if it has no code Yes.
"Spec"You must use curly braces in a if/else/for/while/do statement, even if there is only one line of code, to avoid using the following form: if (condition) statements;
"Spec"Recommend as little else as possible, If-else way can be written as: if (condition) {... return obj;}//Continue to write else business logic code; Note: If you must use the IF () ... else if () ... else ... Way to express logic, "mandatory" do not exceed 3 levels, more than use the state design mode or the Guardian statement. Guardian Statement Example:
public void today () {if (IsBusy ()) {
System.out.println (???);
if (Isfree ()) {
System.out.println ("Go to travel.");
return; 
}
System.out.println ("Stay at home to learn Alibaba Java coding guidelines.");
return; 
}



"Spec"In addition to the common methods (such as getxxx/isxxx), do not execute other complex statements in the conditional judgment, and assign the result of the complex logic judgment to a meaningful Boolean variable name to improve readability. NOTE: Many if statements within the logic is quite complex, the reader needs to analyze the final results of the conditional expression to clarify what kind of conditions to execute what kind of statement, then, if read the reader analysis of logical expression errors? Positive example://Pseudo code as follows Boolean existed = (File.Open (fileName, "w")!= null) && (...) | | (...); if (existed) {...} anti-Example: if (File.Open (FileName, "w")!= null) && (...) | | (...)) { ... }
"Spec"The scenario in the method requiring parameter verification: 1 The method of calling frequency is low. 2 The execution time is expensive method, the parameter check time is negligible, but if because the parameter error causes the intermediate execution rollback, or the mistake, that outweighs the gain. 3 requires a very high stability and availability approach. 4 Externally provided open interface, whether it is Rpc/api/http interface. 5 access to sensitive permissions.
"Spec"The scenario in the method that does not require a parameter checksum: 1 is a method that is most likely to be called, and does not recommend that the parameter be validated. However, external parameter checking must be indicated in the method description. 2 The bottom of the method call frequency is relatively high, generally not check. After all, like the last of pure water filtration, parametric errors are unlikely to go to the bottom to expose the problem. The general DAO layer and Service layer are in the same application, deployed in the same server, so DAO's parameter checksum can be omitted. 3 The method that is declared as private will only be invoked by its own code, and if it is possible to determine that the code passed in the calling method has been checked or is definitely not a problem, the parameter can not be validated at this time.
Annotation Statute "Spec"Comments on classes, class attributes, class methods must use the Javadoc specification,/** content/* format, and//xxx methods are not allowed.
"Spec"All abstract methods, including interfaces

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.