1. [Forced] All programming-related naming cannot start with underscores or dollar signs, nor can they end with underscores or dollar signs. Counterexample: _name/__name/$Object/name_/name$/Object$
2. [Mandatory] All programming-related naming methods are strictly prohibited from using the method of mixing pinyin and English, and it is not allowed to use Chinese directly. Note: Correct English spelling and grammar can make it easy for readers to understand and avoid ambiguity. Note that even pure pinyin naming methods should be avoided.
Counterexample: DaZhePromotion [discount] / getPingfenByName() [rating] / int variable = 3; Positive example: internationally common names such as ali / alibaba / taobao /cainiao / aliyun / youku / hangzhou can be regarded as English.
3. [Forced] The class name uses the UpperCamelCase style and must follow the camel form, with exceptions in the following cases: (relevant naming of the domain model) DO/DTO/VO/DAO, etc.
Positive example: MarcoPolo/UserDO/XmlService/TcpUdpDeal/TaPromotion Counter example: macroPolo/UserDo/XMLService/TCPUDPDeal/TAPromotion
4. [Forced] Method names, parameter names, member variables, and local variables are uniformly used in lowerCamelCase style and must follow the camel form.
Positive example: localValue/getHttpMessage()/inputUserId
5. [Forced] Constant naming is in all capitals, and words are separated by underscores, so as to strive to express the semantics completely and clearly, and do not think that the name is long. Positive example: MAX_STOCK_COUNT Counter example: MAX_COUNT
6. [Forcing] Abstract class naming begins with Abstract or Base; exception class naming ends with Exception; test class naming begins with the name of the class it is to test and ends with Test.
7. [Forced] Brackets are part of the array type, and the array is defined as follows: String[] args; Counterexample: Do not use String args[] to define
8. [Forcing] Do not add is to any Boolean variable in the POJO class, otherwise some framework parsing will cause serialization errors.
Counterexample: defined as the basic data type boolean isSuccess; property, its method isSuccess(), RPC
When the framework re-parses, it "thinks" the corresponding attribute name is success, which causes the attribute to be unable to be obtained, and then throws an exception.
9. [Forced] Package names are uniformly used in lowercase, and there is only one natural semantic English word between dot separators. Package names use singular forms, but if the class name has a plural meaning, the class name can use plural forms.
Positive example: The application tool class package name is com.alibaba.mpp.util, and the class name is MessageUtils (this rule refers to the framework structure of spring)
10. [Forced] Eliminate completely irregular abbreviations and avoid looking at the text without knowing the meaning.
Counterexample: <a certain business code>AbstractClass "abbreviation" is named AbsClass; condition "abbreviation" is named condi. Such random abbreviations seriously reduce the readability of the code.
11. [Recommended] If the design pattern is used, it is recommended to reflect the specific pattern in the class name.
Note: Embodying the design pattern in the name will help readers quickly understand the architectural design ideas.
Positive example: public class OrderFactory; public class LoginProxy;
public classResourceObserver;
12. [Recommended] Do not add any modifiers to methods and attributes in interface classes (not add public either), keep the code simplicity, and add valid javadoc comments. Try not to define variables in the interface. If you must define variables, they must be related to the interface method and are the basic constants of the entire application.
Positive example: Interface method signature: void f();
The basic constant representation of interface: String COMPANY = "alibaba";
Counterexample: Interface method definition: public abstract void f();
Note: The interface allows default implementation in JDK8, so this default method is a default implementation that has value for all implementation classes.
13. There are two sets of rules for naming interfaces and implementation classes:
1) [Mandatory] For Service and DAO classes, based on the concept of SOA, the exposed services must be interfaces. The internal implementation classes use the suffix of Impl and the interfaces.
The positive example: CacheServiceImpl implements the CacheService interface.
2) [Recommended] If it is an interface name that describes ability, use the corresponding adjective as the interface name (usually in the form of able).
Positive example: AbstractTranslator implements Translatable.
14. [Reference] It is recommended to have the Enum suffix for enum class names. Enum member names need to be fully capitalized and separated by underscores.
Note: Enumeration is actually a special constant class, and the constructor is forced to be private by default.
Example: Enumeration name: DealStatusEnum; Member name: SUCCESS / UNKOWN_REASON.
15. [Reference] Naming regulations for each layer:
A) Service/DAO layer method naming regulations
1) The method to obtain a single object is prefixed with get.
2) The method to obtain multiple objects is prefixed with list.
3) The method to obtain statistical values is prefixed with count.
4) The insert method is prefixed with save (recommended) or insert.
5) The delete method is prefixed with remove (recommended) or delete.
6) The modified method is prefixed with update.
B) Domain model naming regulations
1) Data object: xxxDO, xxx is the data table name.
2) Data transmission object: xxxDTO, xxx is the name related to the business field.
3) Display object: xxxVO, xxx is generally the web page name.
4) POJO is a general term for DO/DTO/BO/VO, and it is prohibited to be named xxxPOJO.
1. [Forced] No magic value (i.e., undefined constants) is allowed to appear directly in the code.
Counterexample: String key="Id#taobao_"+tradeId; cache.put(key, value);
2. [Forced] When the initial assignment of long or Long, uppercase L must be used, and cannot be lowercase l. Lowercase is easily confused with the number 1, causing misunderstanding.
Description: Longa = 2l; Is it written with the number 21 or the Long type 2?
3. [Recommended] Do not use a constant class to maintain all constants. It should be classified according to the constant function and maintained separately. For example, cache-related constants are placed under class: CacheConsts; system configuration-related constants are placed under class: ConfigConsts.
Note: A large and comprehensive constant class must be located at modified constants with ctrl+f, which is not conducive to understanding and maintenance.
4. [Recommended] There are five levels of reuse of constants: shared constants across applications, shared constants within applications, shared constants within subprojects, shared constants within packages, and shared constants within classes.
1) Cross-application sharing constants: placed in the two-party library, usually in the const directory in client.jar.
2) In-app sharing constants: placed in the const directory in the modules of one library.
Counterexample: Easy-to-understand variables should also be defined as shared constants within the application. The two siegemen defined variables that represent "yes" in two classes:
In class A: public static final String YES ="yes"; In class B: public static final String YES = "y";
A.YES.equals(B.YES), expected to be true, but actually returns to false, causing online problems.
3) Shared constants within the subproject: that is, in the const directory of the current subproject.
4) Shared constants in packages: that is, in a separate const directory under the current package.
5) Shared constants within the class: define private static final directly inside the class.
5. [Recommended] If the variable value changes within only one range, use the Enum class. If it also has an extended attribute other than the name, the Enum class must be used. The number in the following positive example is the extension information, indicating the day of the week.
Positive examples: public Enum{ MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5),
SATURDAY(6), SUNDAY(7);}
1. [Forced] Convention on the use of braces. If the braces are empty, then it is simply written as {} without any line breaks; if it is a non-empty code block, then:
1) No line break before the left brace.
2) Bring the line after the left brace.
3) Bring before the close brace.
4) If there is code such as else after the closing brace, it does not break the line; it means that the line must be broken after the closing brace is terminated.
2. [Forced] There is no space between the left bracket and the next character; similarly, there is no space between the right bracket and the previous character. For details, please refer to the correct example tips below Article 5.
3. [Forced] Spaces must be added between reserved words such as / for/while/switch/do and left and right brackets.
4. [Forced] Any operator must add a space left and right.
Description: Operators include assignment operator =, logical operator &&, addition, subtraction, multiplication and division symbols, trigonometric operation characters, etc.
5. [Forced] The code block is indented by 4 spaces. If tab is indented, please set it to 1 tab to 4 spaces.
Positive example: (involved 1-5 points)
public static void main(String args[]){
// Indent 4 spaces
String says ="hello";
// There must be a space on the left and right of the operator
int flag = 0;
// There must be a space between the keyword if and brackets, f and the left brackets in the brackets, and no spaces are needed for 1 and the closing brackets if (flag == 0) {
System.out.println(say);
}
// Add space before the left brace and do not wrap the line; add line after the left brace
if (flag == 1){
System.out.println("world");
// Break the line before the closing brace, and there is else after the closing brace, so there is no need to break the line
} else{
System.out.println("ok");
// As the ending brace, you must wrap the line
}
}
6. [Forced] The limit on the number of characters in a single line should not exceed 120, which exceeds the need for a new line. When a new line is broken, the following principles are followed: 1) When a new line is broken, 4 spaces are indented relative to the previous line.
2) Operators are wrapped with the following text.
3) The dot symbol of the method call is wrapped with the following text.
4) Bring lines after multiple parameters are too long and commas.
5) Do not wrap lines before brackets, see counterexamples. A positive example:
StringBuffer sb = new StringBuffer();
//If there are more than 120 characters, the line break is indented by 4 spaces, and the dot symbol before the method is broken together sb.append("zi").append("xin")…
.append("huang");
Counterexample:
StringBuffer sb = new StringBuffer();
//If there are more than 120 characters, do not wrap the line before the brackets
sb.append("zi").append("xin").append...append
("huang");
//The method calls with many parameters exceed 120 characters, and the method after the comma is the newline method(args1,args2, args3, ...
, argsX);
7. [Forced] When defining and passing in method parameters, multiple parameters commas must be added with spaces after them.
For example: In the following example, the actual parameter "a" must have a space after it.
method("a", "b","c");
8. [Recommended] There is no need to add several spaces to align the characters of a certain line with the corresponding characters of the previous line.
A positive example:
int a = 3;
long b = 4L;
float c = 5F;
StringBuffer sb = new StringBuffer();
Note: If you need to align the variable sb, you need to add a few spaces to a, b, and c. In the case of more variables, it is a cumbersome thing.
9. [Force] The text file encoding of the IDE is set to UTF-8; the newline characters of the files in the IDE are in Unix format, and do not use windows format.
10. [Recommended] Insert a blank line between execution statement groups, variable definition statement groups, different business logics, or different semantics in the method body. There is no need to insert blank lines between the same business logic and semantics.
Note: There is no need to insert multiple rows of spaces to separate them.
1. [Forced] Avoid accessing such static variables or static methods through object references of a class, which does not require increasing the compiler resolution cost and directly access using the class name.
2. [Forced] All overwrite methods must be annotated with @Override.
Counterexample: The problem of getObject() and get0bject(). One is O of the letter and the other is 0 of the number. Adding @Override can accurately determine whether the coverage is successful. In addition, if the method signature is modified in the abstract class, its implementation class will immediately compile and report an error.
3. [Forced] Only with the same parameter type and the same business meaning can Java variable parameters be used to avoid using Object.
Description: Variable parameters must be placed at the end of the parameter list. (People are encouraged to try not to use variable parameter programming)
Positive example: public User getUsers(Stringtype, Integer... ids);
4. [Forced] In principle, the method signature is not allowed to be modified to avoid affecting the interface caller. The interface is outdated and must be annotated @Deprecated and clearly state what the new interface or service is used.
5. [Forced] Outdated classes or methods cannot be used.
Description: The method decode(StringencodeStr) in java.net.URLDecoder is outdated and should use double-argument decode(String source, Stringencode). Since the interface provider is clearly an outdated interface, it is obliged to provide a new interface at the same time; as the caller, it is obliged to verify what the new implementation of the outdated method is.
6. [Forcing] Object's equals method is prone to throw empty pointer exceptions, and equals should be called using constants or objects that determine value.
Positive example: "test".equals(object);
Counterexample: object.equals("test");
Note: It is recommended to use java.util.Objects#equals (the tool class introduced by JDK7)
7. [Forcing] Comparison of values between all wrapper objects of the same type, all are compared using the equals method.
Note: For the assignment of Integer var=? between -128 and 127, the Integer object is generated in IntegerCache.cache, and the existing objects will be reused. The Integer value in this interval can be directly judged using ==, but all data outside this interval will be generated on the heap and existing objects will not be reused. This is a big pit. It is recommended to use the equals method for judgment.
8. [Mandatory] The standards for using basic data types and packaging data types are as follows:
1) All POJO class attributes must use wrapper data type.
2) The return value and parameters of the RPC method must use the wrapper data type.
3) It is recommended to use basic data types for all local variables.
Note: The POJO class attribute has no initial value, which reminds the user that he must explicitly assign values by himself when he needs to use it.
NPE problems, or inventory inspection, are guaranteed by the user.
Positive example: The query result of the database may be null, because it is automatically unboxed, and receiving with basic data types is risky. Counterexample: The transaction report of a certain business shows the rise and fall of the total transaction amount, that is, positive and negative x%, x is the basic data type. When the call is unsuccessful, the default value is returned, and the page displays: 0%, which is unreasonable and should be displayed as a mid-score-. Therefore, the null value of the wrapper data type can represent additional information, such as: the remote call failed and the exception exit.
9. [Forced] When defining POJO classes such as DO/DTO/VO, do not set any attribute default values.
Counterexample: The default value of gmtCreate of a business is newDate(); however, this property does not place a specific value when extracting data. This field is updated when updating other fields, resulting in the creation time being modified to the current time.
10. [Forced] When adding new attributes to the serialization class, please do not modify the serialVersionUID field to avoid deserialization failure; if the upgrade is completely incompatible and avoid deserialization chaos, please change the serialVersionUID value.
Note: Note that if serialVersionUID is inconsistent, a serialization runtime exception will be thrown.
11. [Forced] Any business logic is prohibited from being added to the construction method. If there is initialization logic, please put it in the init method.
12. [Forced] The toString method must be written for the POJO class. When using the tool class source> generate toString, if you inherit another POJO class, please add super.toString in front.
Note: When an exception is thrown by the method execution, you can directly call POJO's toString() method to print its attribute value, which is convenient for troubleshooting.
13. [Recommended] When using index to access the array obtained by String's split method, you need to check whether there is any content after the last delimiter, otherwise there will be a risk of throwing IndexOutOfBoundsException.
illustrate:
String str = "a,b,c,,"; String[] ary =str.split(",");
//The expected greater than 3, the result is 3
System.out.println(ary.length);
14. [Recommended] When a class has multiple constructors, or multiple methods of the same name, these methods should be placed together in order for easy reading.
15. [Recommended] The order of method definitions within the class is: public method or protection method > private method > getter/setter method.
Note: Public methods are the most concerned methods for class callers and maintainers, and the first screen is best displayed; although the protection method is only concerned with subclasses, it may also be the core method under the "template design mode"; while private methods generally do not need to be particularly concerned outside, and are a black box implementation; because the method information is low, all Service and DAO getter/setter methods are placed at the end of the class body.
16. [Recommended] In the setter method, the parameter name is the same as the class member variable name, this. Member name = parameter name. In the getter/setter method, try not to increase business logic and increase the difficulty of troubleshooting problems.
Counterexample:
public IntegergetData(){ if(true) { return data +100;
} else { return data- 100;
} }
17. [Recommended] The connection method of strings in the loop body is expanded using StringBuilder's append method.
Counterexample:
String str ="start"; for(int i=0; i<100;i++){ str = str +"hello";
}
Note: The decompiled bytecode file shows that each loop will new StringBuilder object, then perform an append operation, and finally return the String object through the toString method, causing waste of memory resources.
18. [Recommended] Final can improve program response efficiency and declare it as final: 1) Variables that do not require reassignment, including class attributes and local variables.
2) Add final before the object parameters, which means that the reference's pointer is not allowed to be modified.
3) Class method determines that it is not allowed to be rewritten.
19. [Recommended] Use the Object clone method with caution to copy objects.
Note: The clone method of the object is a shallow copy by default. If you want to achieve deep copy, you need to rewrite the clone method to implement the copy of the attribute object.
20. [Recommended] Class members and methods have strict access control:
1) If the external object is not allowed to be created directly through new, the constructor must be private.
2) The tool class does not allow public or default constructor methods.
3) The class is not static member variable and is shared with the subclass and must be protected.
4) Classes are not static member variables and are only used in this class and must be private.
5) If the class static member variable is only used in this class, it must be private.
6) If it is a static member variable, it must be considered whether it is final.
7) Class member methods are only for internal calls of the class and must be private.
8) Class member methods are only exposed to inherited classes, so they are restricted to protected.
Description: Any class, method, parameters, variables, strictly control the access scope. Too wide access scope is not conducive to module decoupling. Thinking: If it is a private method, delete it if you want to delete it. But if you delete it, do you have to sweat a little while your palms? Variables are like your own children, try to be within your own sight. The scope of the variables is too large. If you run around without restrictions, then you will be worried.
1. [Forced] When the key of Map/Set is a custom object, hashCode and equals must be rewritten.
Formal example: String rewrites hashCode and equals methods, so we can use String objects very happily as keys.
2. [Forced] The result of the subList of ArrayList cannot be forced to ArrayList, otherwise a ClassCastException will be thrown: java.util.RandomAccessSubList cannot be cast to java.util.ArrayList; Note: subList returns the inner class SubList of ArrayList, not ArrayList, but a view of ArrayList. All operations on the SubList sublist will eventually be reflected on the original list.
3. [Forcing] In the subList scenario, pay close attention to modifying the number of original set elements, which will cause the traversal, addition and deletion of the sublist to generate ConcurrentModificationException exceptions.
4. [Forcing] To use the method of converting collections to arrays, you must use the toArray(T[] array) of the collection. The array of types is passed in is an array of exactly the same size, and the size is list.size().
Counterexample: There is a problem with using the toArray method directly without parameters. The return value of this method can only be the Object[] class. If you forcefully convert another type of array, a ClassCastException error will occur. A positive example:
List<String> list = newArrayList<String>(2); list.add("guan"); list.add("bao");
String[] array = newString[list.size()]; array =list.toArray(array);
Note: Using the toArray parameter method, when the array space allocated to the parameter is not large enough, the toArray method will reallocate memory space and return the new array address; if the array element is larger than the actual requirement, the array element subscripted as [list.size()] will be set to null, and other array elements retain the original value. Therefore, it is best to define the method into the parameter group size consistent with the number of set elements.
5. [Forced] When converting an array into a collection using the tool class Arrays.asList(), it cannot use it to modify the methods related to the collection. Its add/remove/clear method will throw an UnsupportedOperationException exception.
Description: The return object of asList is an Arrays internal class and does not implement the modification method of the collection. Arrays.asList reflects the adapter mode, which is just a conversion interface, and the data in the background is still an array.
String[] str = new String[] {"a", "b" };
List list = Arrays.asList(str);
The first case: list.add("c"); runtime exception. The second case: str[0]= "gujin"; then list.get(0) will also be modified accordingly.
6. [Forced] The generic wildcard character <? extends T> is used to receive the returned data. The generic collection of this method cannot use the add method. Note: After the apple is packed, it returns a <? extends Fruits> object. This object cannot add any fruit, including apples.
7. [Forced] Do not remove/add operations of elements in the foreach loop. Please use the Iterator method to remove the element. If the operation is concurrent, you need to lock the Iterator object.
Counterexample:
List<String> a = newArrayList<String>();
a.add("1");
a.add("2"); for(String temp : a) { if("1".equals(temp)) {
a.remove(temp);
}
}
Note: The execution result of this example will be beyond everyone's expectations. So if you try to replace "1" with "2", will it be the same result? A positive example:
Iterator<String> it = a.iterator(); while(it.hasNext()){
String temp = it.next(); if (condition for deleting elements) { it.remove();
}
}
8. [Forced] On JDK7 version or above, Comparator must satisfy reflexivity, transitiveness, and symmetry, otherwise Arrays.sort,
Collections.sort will report an IllegalArgumentException exception.
illustrate:
1) Reflexivity: The comparison results of x and y are the opposite of the comparison results of y and x.
2) Transmission: x>y,y>z, then x>z.
3) Symmetry: x=y, then the comparison result of x and z is the same as that of y. Counterexample: The following example does not handle equality, and an exception may occur during actual use:
new Comparator<Student>(){
@Override publicint compare(Student o1, Student o2){ return o1.getId() > o2.getId() ? 1 :-1; }
}
9. [Recommended] When initializing a collection, try to specify the initial value of the collection. Note: Try to initialize ArrayList with ArrayList(int initialCapacity) as much as possible.
10. [Recommended] Use entrySet to traverse the Map class collection KV, rather than the keySet method for traversal.
Note: The keySet actually traversed twice, one is converted to an Iterator object, and the other is to take out the value corresponding to the key from the hashMap. The entrySet just traversed once and puts both the key and value into the entry, which is more efficient. If it is JDK8, use the Map.foreach method.
For example: values() returns a V value set, which is a list collection object; keySet() returns a K value set, which is a Set collection object; entrySet() returns a KV value combination set.
11. [Recommended] Pay great attention to whether the Map class set K/V can store null values, as shown in the following table:
12. [Reference] Make rational use of the order and stability of the set to avoid the negative impact of the disorder and unstability of the set.
Note: Stability means that the order of elements of the set is certain for each traversal. Order means that the results of traversal are arranged in sequence according to some comparison rule. For example: ArrayList is order/unsort; HashMap is unorder/unsort; TreeSet is order/sort.
13. [Reference] Using the unique characteristics of the Set element, you can quickly deduplicate another set, avoiding the use of List's contains method for traversal deduplication.
1. [Forced] It is thread-safe to obtain singleton objects. Operations in singleton objects must also ensure thread safety.
Note: Resource-driven classes, tool classes, and singleton factory classes need to be paid attention to.
2. [Forced] Thread resources must be provided through thread pools, and it is not allowed to explicitly create threads in the application.
Note: The advantage of using thread pools is to reduce the time spent on creating and destroying threads and the overhead of system resources, and solve the problem of insufficient resources. If you do not use thread pools, it may cause the system to create a large number of similar threads, resulting in memory consumption or "overswitching".
3. [Forcing] SimpleDateFormat is a thread-insecure class. It is generally not defined as a static variable. If it is defined as static, it must be locked, or the DateUtils tool class must be used.
Positive example: Pay attention to thread safety and use DateUtils. It is also recommended to handle the following:
private static final ThreadLocal<DateFormat> df =new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue(){
return newSimpleDateFormat("yyyy-MM-dd");
}
};
Note: If it is a JDK8 application, you can use instant instead of Date and Localdatetime instead of Calendar.
Datetimeformatter replaces Simpledateformatter, the official explanation is: simple beautiful strong immutable thread-safe.
4. [Forced] When high concurrency is high, synchronous calls should consider the performance loss of the lock. If you can use a lock-free data structure, don’t use a lock; if you can lock blocks, don’t use a whole method body; if you can use an object lock, don’t use a class lock.
5. [Forced] When locking multiple resources, database tables, and objects at the same time, a consistent locking order is required, otherwise deadlocks may occur.
Note: Thread 1 needs to lock tables A, B, and C in sequence before updating operations can be performed. Then the locking order of thread 2 must also be A, B, and C, otherwise deadlocks may occur.
6. [Forced] When modifying the same record concurrently, avoid update loss. Either add locks at the application layer, locks in the cache, or use optimistic locks at the database layer, using version as the basis for updates. Note: If the probability of conflict per access is less than 20%, it is recommended to use optimistic locks, otherwise use pessimistic locks. The number of retrys of optimistic locks must not be less than 3 times.
7. [Forced] When multi-threading timed tasks are processed in parallel, when Timer runs multiple TimeTasks, as long as one of them does not catch the thrown exception, the other tasks will automatically terminate. There is no problem using ScheduledExecutorService.
8. [Forced] Thread pools are not allowed to be created using Executors, but are used by ThreadPoolExecutor. This processing method allows students who write to more clearly define the running rules of thread pools and avoid the risk of resource exhaustion.
Description: Disadvantages of Executors methods:
1) newFixedThreadPool and newSingleThreadExecutor: The main problem is that stacked request processing queues can consume very much memory, even OOM.
2) newCachedThreadPool and newScheduledThreadPool: The main problem is that the maximum number of threads is Integer.MAX_VALUE, which may create a very large number of threads, or even OOM.
9. [Forced] Please specify a meaningful thread name when creating a thread or thread pool to facilitate backtracking when an error occurs.
A positive example:
public class TimerTaskThread extends Thread{ publicTimerTaskThread(){ super.setName("TimerTaskThread"); …
}
10. [Recommended] Use CountDownLatch for asynchronous to synchronous operation. Each thread must call the countDown method before exiting. Pay attention to catch exceptions when executing code to ensure that the countDown method can be executed, so as to avoid the main thread being unable to execute to the countDown method and not return the result until the timeout. Note: Note that the child thread throws an exception stack and cannot be tried-catched in the main thread.
11. [Recommended] Avoid using Random instances by multiple threads. Although sharing the instance is thread-safe, performance degradation will occur due to competition for the same seed. Description: Random instances include instances of java.util.Random or Math.random() instance.
Formal example: After JDK7, you can directly use the API ThreadLocalRandom. Before JDK7, you can make one instance per thread.
12. [Recommended] The potential problems of optimization problems that achieve delayed initialization through double-checked locking (in concurrent scenarios) (refer to The "Double-Checked Locking is Broken" Declaration). The simpler solution for the recommended problem (applicable to jdk5 and above), declare the target attribute as volatile (for example, in the counterexample, the attribute of modifying helper is declared as private volatile helper helper= null;); counterexample:
class Foo { private Helper helper = null; public Helper getHelper() {
if (helper ==null) synchronized(this) { if (helper== null) helper = newHelper();
} return helper; }
// other functions and members...
}
13. [Reference] volatile solves the problem of multi-threaded memory invisibility. For one write and multiple reads, it can solve the problem of variable synchronization, but if you write more, it cannot solve the thread safety problem. If you want to retrieve count++ data, use the following class to implement it:
AtomicIntegercount = new AtomicInteger(); count.addAndGet(1); count++ operation if it is
JDK8, recommended to use LongAdder object, perform better than AtomicLong (reduces the number of retrys of optimistic locks).
14. [Reference] Pay attention to the problem of HashMap's expansion dead link, which leads to the CPU soaring.
15. [Reference] ThreadLocal cannot solve the problem of updating shared objects. It is recommended to use static modification for ThreadLocal objects. This variable is shared by all operations in a thread, so it is set as a static variable. All such instances share this static variable, that is, when the class is first used, only one piece of storage space is allocated, and all such objects (as long as they are defined in this thread) can manipulate this variable.
1. [Forced] In a switch block, each case will either be terminated by break/return, or comment to indicate which case the program will continue to execute; in a switch block, a default statement must be included and placed at the end, even if it has no code.
2. [Forced] Braces must be used in the if/else/for/while/do statement, even if there is only one line of code, avoid the following form: if (condition) statements;
3. [Recommended] It is recommended to use else as little as possible. If-else method can be rewritten as:
if(condition){ … return obj; }
// Then write the business logic code of else;
Note: If you want to express logic in the if-else way, [Forced] do not exceed 3 layers. Please use the status design mode if you exceed the status.
4. [Recommended] Except for common methods (such as getXxx/isXxx), do not execute complex statements in conditional judgments to improve readability. A positive example:
//The pseudo code is as follows
InputStream stream = file.open(fileName,"w");
if (stream != null) {
…
} Counterexample:
if (file.open(fileName, "w") != null)){
…
}
5. [Recommended] The statements in the loop body should consider performance. Try to move the following operations to the loop body for processing as much as possible, such as defining objects, variables,
Get the database connection and perform unnecessary try-catch operations (will this try-catch be moved outside the loop).
6. [Recommended] Interface reference protection, a common interface for batch operations in this scenario.
7. [Reference] Scenarios where parameter verification is required in the method:
1) Methods with low frequency calls.
2) The execution time is very expensive, and the parameter verification time is almost negligible, but if the intermediate execution rollback or error is caused by parameter error, it will not be worth the effort. 3) A method that requires extremely high stability and usability.
4) Open interface provided to the outside world, whether it is the RPC/API/HTTP interface.
8. [Reference] Scenarios in the method where parameter verification is not required:
1) Methods that are most likely to be called by loops, and it is not recommended to verify parameters. However, external parameter checks must be indicated in the method description.
2) The frequency of calling methods at the bottom is relatively high and generally not verified. After all, it is the last step like pure water filtration, and it is unlikely that the problem will be exposed to the bottom layer. Generally, the DAO layer and the Service layer are in the same application and are deployed in the same server, so the DAO parameter verification can be omitted.
3) Methods declared as private will only be called by their own code. If you can confirm that the incoming parameters of the code calling the method have been checked or there will definitely be no problem, you can not verify the parameters at this time.
1. [Forced] Comments to classes, class attributes, and class methods must use the javadoc specification, use the /** content*/ format, and must not be used.
//xxx mode.
Note: In the IDE editing window, the javadoc method will prompt relevant annotations, and generating javadoc can correctly output the corresponding annotations; in the IDE, when the project calls a method, the meaning of the method, parameters, and return values can be suspended without entering the method, and improve reading efficiency.
2. [Forcing] All abstract methods (including methods in the interface) must be commented with javadoc. In addition to returning values, parameters, and exception descriptions, they must also point out what the method does and what functions it implements.
Note: If there are any precautions for implementation and call, please explain them together.
3. [Forced] All classes must add creator information.
4. [Forced] The method has a single line comment, starting a new line above the commented statement, using // comment. Multi-line comments inside the method use /* */ comments, pay attention to aligning with the code.
5. [Forced] All enum type fields must have comments to indicate the purpose of each data item.
6. [Recommended] Instead of annotating "half-baked" in English, it is better to explain the problem clearly in Chinese annotations. For proper nouns and keywords, just keep the original English text.
Counterexample: "TCP connection timeout" is interpreted as "transmission control protocol connection timeout", and understanding it is a brain-consuming task.
7. [Recommended] While modifying the code, the annotations must also be modified accordingly, especially the modification of parameters, return values, exceptions, core logic, etc.
说明:代码与注释更新不同步,就像路网与导航软件更新不同步一样,如果导航软件严重滞后,就失去了导航的意义。
8. 【参考】注释掉的代码尽量要配合说明,而不是简单的注释掉。
说明:代码被注释掉有两种可能性:1)后续会恢复此段代码逻辑。2)永久不用。前者如果没有备注信息,难以知晓注释动机。后者建议直接删掉(代码仓库保存了历史代码)。
9. 【参考】对于注释的要求:第一、能够准确反应设计思想和代码逻辑;第二、能够描述业务含义,使别的程序员能够迅速了解到代码背后的信息。完全没有注释的大段代码对于阅读者形同天书,注释是给自己看的,即使隔很长时间,也能清晰理解当时的思路;注释也是给继任者看的,使其能够快速接替自己的工作。
10.【参考】好的命名、代码结构是自解释的,注释力求精简准确、表达到位。避免出现注释的一个极端:过多过滥的注释,代码的逻辑一旦修改,修改注释是相当大的负担。
反例:
// put elephant into fridge put(elephant,fridge);
方法名put,加上两个有意义的变量名elephant和fridge,已经说明了这是在干什么,语义清晰的代码不需要额外的注释。
11.【参考】特殊注释标记,请注明标记人与标记时间。注意及时处理这些标记,通过标记扫描,经常清理此类标记。线上故障有时候就是来源于这些标记处的代码。 1) 待办事宜(TODO):( 标记人,标记时间,[预计处理时间])
表示需要实现,但目前还未实现的功能。这实际上是一个javadoc的标签,目前的
javadoc还没有实现,但已经被广泛使用。只能应用于类,接口和方法(因为它是一个javadoc标签)。
2)错误,不能工作(FIXME):(标记人,标记时间,[预计处理时间])
在注释中用FIXME标记某代码是错误的,而且不能工作,需要及时纠正的情况。
1. 【强制】在使用正则表达式时,利用好其预编译功能,可以有效加快正则匹配速度。
说明:不要在方法体内定义:Pattern pattern = Pattern.compile(规则);
2. 【强制】避免用Apache Beanutils进行属性的copy。
说明:Apache BeanUtils性能较差,可以使用其他方案比如SpringBeanUtils, Cglib
BeanCopier。
3. 【强制】velocity调用POJO类的属性时,建议直接使用属性名取值即可,模板引擎会自动按规范调用POJO的getXxx(),如果是boolean基本数据类型变量(注意,boolean命名不需要加is前缀),会自动调用isXxx()方法。
说明:注意如果是Boolean包装类对象,优先调用getXxx()的方法。
4. 【强制】后台输送给页面的变量必须加$!{var}――中间的感叹号。
说明:如果var=null或者不存在,那么${var}会直接显示在页面上。
5. 【强制】注意Math.random() 这个方法返回是double类型,注意取值范围0≤x<1(能够取到零值,注意除零异常),如果想获取整数类型的随机数,不要将x放大10的若干倍然后取整,直接使用Random对象的nextInt或者nextLong方法。
6. 【强制】获取当前毫秒数:System.currentTimeMillis(); 而不是new Date().getTime(); 说明:如果想获取更加精确的纳秒级时间值,用System.nanoTime。在JDK8中,针对统计时间等场景,推荐使用Instant类。
7. 【推荐】尽量不要在vm中加入变量声明、逻辑运算符,更不要在vm模板中加入任何复杂的逻辑。
8. 【推荐】任何数据结构的使用都应限制大小。
说明:这点很难完全做到,但很多次的故障都是因为数据结构自增长,结果造成内存被吃光。
9. 【推荐】对于“明确停止使用的代码和配置”,如方法、变量、类、配置文件、动态配置属性等要坚决从程序中清理出去,避免造成过多垃圾。清理这类垃圾代码是技术气场,不要有这样的观念:“不做不错,多做多错”。
1. 【强制】不要捕获Java类库中定义的继承自RuntimeException的运行时异常类,如:
IndexOutOfBoundsException/ NullPointerException,这类异常由程序员预检查来规避,保证程序健壮性。
正例:if(obj != null) {...}
反例:try { obj.method() }catch(NullPointerException e){…}
2. 【强制】异常不要用来做流程控制,条件控制,因为异常的处理效率比条件分支低。
3. 【强制】对大段代码进行try-catch,这是不负责任的表现。catch时请分清稳定代码和非稳定代码,稳定代码指的是无论如何不会出错的代码。对于非稳定代码的catch尽可能进行区分异常类型,再做对应的异常处理。
4. 【强制】捕获异常是为了处理它,不要捕获了却什么都不处理而抛弃之,如果不想处理它,请将该异常抛给它的调用者。最外层的业务使用者,必须处理异常,将其转化为用户可以理解的内容。
5. 【强制】有try块放到了事务代码中,catch异常后,如果需要回滚事务,一定要注意手动回滚事务。
6. 【强制】finally块必须对资源对象、流对象进行关闭,有异常也要做try-catch。
说明:如果JDK7,可以使用try-with-resources方法。
7. 【强制】不能在finally块中使用return,finally块中的return返回后方法结束执行,不会再执行try块中的return语句。
8. 【强制】捕获异常与抛异常,必须是完全匹配,或者捕获异常是抛异常的父类。
说明:如果预期抛的是绣球,实际接到的是铅球,就会产生意外情况。
9. 【推荐】方法的返回值可以为null,不强制返回空集合,或者空对象等,必须添加注释充分说明什么情况下会返回null值。调用方需要进行null判断防止NPE问题。
说明:本规约明确防止NPE是调用者的责任。即使被调用方法返回空集合或者空对象,对调用者来说,也并非高枕无忧,必须考虑到远程调用失败,运行时异常等场景返回null的情况。
10.【推荐】防止NPE,是程序员的基本修养,注意NPE产生的场景:
1) 返回类型为包装数据类型,有可能是null,返回int值时注意判空。
反例:public int f(){return Integer对象},如果为null,自动解箱抛NPE。
2) 数据库的查询结果可能为null。
3) 集合里的元素即使isNotEmpty,取出的数据元素也可能为null。
4) 远程调用返回对象,一律要求进行NPE判断。
5) 对于Session中获取的数据,建议NPE检查,避免空指针。
6) 级联调用obj.getA().getB().getC();一连串调用,易产生NPE。
11.【推荐】在代码中使用“抛异常”还是“返回错误码”,对于公司外的http/api开放接口必须使用“错误码”;而应用内部推荐异常抛出;跨应用间RPC调用优先考虑使用Result方式,封装isSuccess、“错误码”、“错误简短信息”。
说明:关于RPC方法返回方式使用Result方式的理由:
1) 使用抛异常返回方式,调用方如果没有捕获到就会产生运行时错误。
2) 如果不加栈信息,只是new自定义异常,加入自己的理解的error message,对于调用端解决问题的帮助不会太多。如果加了栈信息,在频繁调用出错的情况下,数据序列化和传输的性能损耗也是问题。
12.【推荐】定义时区分unchecked / checked 异常,避免直接使用RuntimeException抛出,更不允许抛出Exception或者Throwable,应使用有业务含义的自定义异常。推荐业界已定义过的自定义异常,如:DaoException / ServiceException等。
13.【参考】避免出现重复的代码(Don'tRepeat Yourself),即DRY原则。
说明:随意复制和粘贴代码,必然会导致代码的重复,在以后需要修改时,需要修改所有的副本,容易遗漏。必要时抽取共性方法,或者抽象公共类,甚至是共用模块。
正例:一个类中有多个public方法,都需要进行数行相同的参数校验操作,这个时候请抽取:
private boolean checkParam(DTO dto){...}
1. 【强制】应用中不可直接使用日志系统(Log4j、Logback)中的API,而应依赖使用日志框架
SLF4J中的API,使用门面模式的日志框架,有利于维护和各个类的日志处理方式统一。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger =LoggerFactory.getLogger(Abc.class);
2. 【强制】日志文件推荐至少保存15天,因为有些异常具备以“周”为频次发生的特点。
3. 【强制】应用中的扩展日志(如打点、临时监控、访问日志等)命名方式:
appName_logType_logName.log。logType:日志类型,推荐分类有stats/desc/monitor/visit 等;logName:日志描述。这种命名的好处:通过文件名就可知道日志文件属于什么应用,什么
类型,什么目的,也有利于归类查找。
正例:mppserver应用中单独监控时区转换异常,如: mppserver_monitor_timeZoneConvert.log
说明:推荐对日志进行分类,错误日志和业务日志尽量分开存放,便于开发人员查看,也便于通过日志对系统进行及时监控。
4. 【强制】对trace/debug/info级别的日志输出,必须使用条件输出形式或者使用占位符的方式。
说明:logger.debug("Processingtrade with id: " + id + " symbol: " + symbol); 如果日志级别是warn,上述日志不会打印,但是会执行字符串拼接操作,如果symbol是对象,会执行toString()方法,浪费了系统资源,执行了上述操作,最终日志却没有打印。
正例:(条件)
if (logger.isDebugEnabled()) {
logger.debug("Processing trade with id: " +id + " symbol: " + symbol);
}
正例:(占位符)
logger.debug("Processing trade with id: {} andsymbol : {} ", id, symbol);
5. 【强制】避免重复打印日志,浪费磁盘空间,务必在log4j.xml中设置additivity=false。
正例:<loggername="com.taobao.ecrm.member.config" additivity="false">
6. 【强制】异常信息应该包括两类信息:案发现场信息和异常堆栈信息。如果不处理,那么往上抛。
正例:logger.error(各类参数或者对象toString +"_" + e.getMessage(), e);
7. 输出的POJO类必须重写toString方法,否则只输出此对象的hashCode值(地址值),没啥参考意义。
8. 【推荐】可以使用warn日志级别来记录用户输入参数错误的情况,避免用户投诉时,无所适从。注意日志输出的级别,error级别只记录系统逻辑出错、异常、或者重要的错误信息。如非必要,请不要在此场景打出error级别,避免频繁报警。
9. 【推荐】谨慎地记录日志。生产环境禁止输出debug日志;有选择地输出info日志;如果使用warn来记录刚上线时的业务行为信息,一定要注意日志输出量的问题,避免把服务器磁盘撑爆,并记得及时删除这些观察日志。
说明:大量地输出无效日志,不利于系统性能提升,也不利于快速定位错误点。纪录日志时请思考:这些日志真的有人看吗?看到这条日志你能做什么?能不能给问题排查带来好处?
10.【参考】如果日志用英文描述不清楚,推荐使用中文注释。对于中文UTF-8的日志,在secureCRT 中,set encoding=utf-8;如果中文字符还乱码,请设置:全局>默认的会话设置>外观>字体> 选择字符集gb2312;如果还不行,执行命令:set termencoding=gbk,并且直接使用中文来进行检索。
1. 【强制】表达是与否概念的字段,必须使用is_xxx的方式命名,数据类型是unsigned tinyint
( 1表示是,0表示否),此规则同样适用于odps建表。
说明:任何字段如果为非负数,必须是unsigned。
2. 【强制】表名、字段名必须使用小写字母或数字;禁止出现数字开头,禁止两个下划线中间只出现数字。数据库字段名的修改代价很大,因为无法进行预发布,所以字段名称需要慎重考虑。
正例:getter_admin,task_config,level3_name 反例:GetterAdmin,taskConfig,level_3_name
3. 【强制】表名不使用复数名词。
说明:表名应该仅仅表示表里面的实体内容,不应该表示实体数量,对应于DO类名也是单数形式,符合表达习惯。
4. 【强制】禁用保留字,如desc、range、match、delayed等,参考官方保留字。
5. 【强制】唯一索引名为uk_字段名;普通索引名则为idx_字段名。
说明:uk_即unique key;idx_ 即index的简称。
6. 【强制】小数类型为decimal,禁止使用float和double。
说明:float和double在存储的时候,存在精度损失的问题,很可能在值的比较时,得到不正确的结果。如果存储的数据范围超过decimal的范围,建议将数据拆成整数和小数分开存储。
7. 【强制】如果存储的字符串长度几乎相等,使用CHAR定长字符串类型。
8. 【强制】varchar是可变长字符串,不预先分配存储空间,长度不要超过5000,如果存储长度大于此值,定义字段类型为TEXT,独立出来一张表,用主键来对应,避免影响其它字段索引效率。
9. 【强制】表必备三字段:id, gmt_create, gmt_modified。
说明:其中id必为主键,类型为unsigned bigint、单表时自增、步长为1;分表时改为从
TDDL Sequence取值,确保分表之间的全局唯一。gmt_create,gmt_modified的类型均为date_time类型。
10.【推荐】表的命名最好是加上“业务名称_表的作用”,避免上云梯后,再与其它业务表关联时有混淆。
正例:tiger_task/ tiger_reader / mpp_config
11.【推荐】库名与应用名称尽量一致。
12.【推荐】如果修改字段含义或对字段表示的状态追加时,需要及时更新字段注释。
13.【推荐】字段允许适当冗余,以提高性能,但是必须考虑数据同步的情况。冗余字段应遵循:
1) 不是频繁修改的字段。
2) 不是varchar超长字段,更不能是text字段。
正例:各业务线经常冗余存储商品名称,避免查询时需要调用IC服务获取。
14.【推荐】单表行数超过500万行或者单表容量超过2GB,才推荐进行分库分表。
说明:如果预计三年后的数据量根本达不到这个级别,请不要在创建表时就分库分表。
反例:某业务三年总数据量才2万行,却分成1024张表,问:你为什么这么设计?答:分1024 张表,不是标配吗?
15.【参考】合适的字符存储长度,不但节约数据库表空间、节约索引存储,更重要的是提升检索速度。
正例:人的年龄用unsigned tinyint(表示范围0-255,人的寿命不会超过255岁);海龟就必须是smallint,但如果是太阳的年龄,就必须是int;如果是所有恒星的年龄都加起来,那么就必须使用bigint。
1. 【强制】业务上具有唯一特性的字段,即使是组合字段,也必须建成唯一索引。
说明:不要以为唯一索引影响了insert速度,这个速度损耗可以忽略,但提高查找速度是明显的;另外,即使在应用层做了非常完善的校验和控制,只要没有唯一索引,根据墨菲定律,必然有脏数据产生。
2. 【强制】超过三个表禁止join。需要join的字段,数据类型保持绝对一致;多表关联查询时,保证被关联的字段需要有索引。
说明:即使双表join也要注意表索引、SQL性能。
3. 【强制】在varchar字段上建立索引时,必须指定索引长度,没必要对全字段建立索引,根据实际文本区分度决定索引长度。
说明:索引的长度与区分度是一对矛盾体,一般对字符串类型数据,长度为20的索引,区分度会高达90%以上,可以使用count(distinct left(列名, 索引长度))/count(*)的区分度来确定。
4. 【强制】页面搜索严禁左模糊或者全模糊,如果需要请走搜索引擎来解决。
说明:索引文件具有B-Tree的最左前缀匹配特性,如果左边的值未确定,那么无法使用此索引。
5. 【推荐】如果有order by的场景,请注意利用索引的有序性。order by 最后的字段是组合索引的一部分,并且放在索引组合顺序的最后,避免出现file_sort的情况,影响查询性能。
正例:where a=? and b=? order by c; 索引:a_b_c
反例:索引中有范围查找,那么索引有序性无法利用,如:WHERE a>10 ORDER BY b; 索引a_b 无法排序。
6. 【推荐】利用覆盖索引来进行查询操作,来避免回表操作。
说明:如果一本书需要知道第11章是什么标题,会翻开第11章对应的那一页吗?目录浏览一下就好,这个目录就是起到覆盖索引的作用。
正例:IDB能够建立索引的种类:主键索引、唯一索引、普通索引,而覆盖索引是一种查询的一种效果,用explain的结果,extra列会出现:using index.
7. 【推荐】利用延迟关联或者子查询优化超多分页场景。
说明:MySQL并不是跳过offset行,而是取offset+N行,然后返回放弃前offset行,返回N 行,那当offset特别大的时候,效率就非常的低下,要么控制返回的总页数,要么对超过特定阈值的页数进行SQL改写。
正例:先快速定位需要获取的id段,然后再关联:
SELECT a.* FROM 表1 a, (select id from表1 where 条件LIMIT 100000,20 ) bwhere a.id=b.id
8. 【推荐】 SQL性能优化的目标:至少要达到range 级别,要求是ref级别,如果可以是consts 最好。 illustrate:
1) consts 单表中最多只有一个匹配行(主键或者唯一索引),在优化阶段即可读取到数据。
2) ref 指的是使用普通的索引。(normalindex)
3) range 对索引进范围检索。
反例:explain表的结果,type=index,索引物理文件全扫描,速度非常慢,这个index级别比较range还低,与全表扫描是小巫见大巫。
9. 【推荐】建组合索引的时候,区分度最高的在最左边。
正例:如果where a=? and b=? ,a列的几乎接近于唯一值,那么只需要单建idx_a索引即可。说明:存在非等号和等号混合判断条件时,在建索引时,请把等号条件的列前置。如:where a>?
and b=? 那么即使a的区分度更高,也必须把b放在索引的最前列。
10.【参考】创建索引时避免有如下极端误解:
1) 误认为一个查询就需要建一个索引。
2) 误认为索引会消耗空间、严重拖慢更新和新增速度。
3) 误认为唯一索引一律需要在应用层通过“先查后插”方式解决。
1. 【强制】不要使用count(列名)或count(常量)来替代count(*),count(*)就是SQL92定义的标准统计行数的语法,跟数据库无关,跟NULL和非NULL无关。
说明:count(*)会统计值为NULL的行,而count(列名)不会统计此列为NULL值的行。
2. 【强制】count(distinct col) 计算该列除NULL之外的不重复数量。注意count(distinct col1, col2) 如果其中一列全为NULL,那么即使另一列有不同的值,也返回为0。
3. 【强制】当某一列的值全是NULL时,count(col)的返回结果为0,但sum(col)的返回结果为
NULL,因此使用sum()时需注意NPE问题。
正例:可以使用如下方式来避免sum的NPE问题:SELECTIF(ISNULL(SUM(g)),0,SUM(g)) FROM table;
4. 【强制】使用ISNULL()来判断是否为NULL值。注意:NULL与任何值的直接比较都为NULL。
illustrate:
1) NULL<>NULL的返回结果是NULL,不是false。
2) NULL=NULL的返回结果是NULL,不是true。
3) NULL<>1的返回结果是NULL,而不是true。
5. 【强制】在代码中写分页查询逻辑时,若count为0应直接返回,避免执行后面的分页语句。
6. 【强制】不得使用外键与级联,一切外键概念必须在应用层解决。
说明:(概念解释)学生表中的student_id是主键,那么成绩表中的student_id则为外键。
如果更新学生表中的student_id,同时触发成绩表中的student_id更新,则为级联更新。外键与级联更新适用于单机低并发,不适合分布式、高并发集群;级联更新是强阻塞,存在数据库更新风暴的风险;外键影响数据库的插入速度。
7. 【强制】禁止使用存储过程,存储过程难以调试和扩展,更没有移植性。
8. 【强制】IDB数据订正时,删除和修改记录时,要先select,避免出现误删除,确认无误才能提交执行。
9. 【推荐】in操作能避免则避免,若实在避免不了,需要仔细评估in后边的集合元素数量,控制在1000个之内。
10.【参考】因阿里巴巴全球化需要,所有的字符存储与表示,均以utf-8编码,那么字符计数方法注意:
illustrate:
SELECT LENGTH("阿里巴巴"); 返回为12
SELECT CHARACTER_LENGTH("阿里巴巴"); 返回为4
如果要使用表情,那么使用utfmb4来进行存储,注意它与utf-8编码。
11.【参考】TRUNCATE TABLE 比DELETE 速度快,且使用的系统和事务日志资源少,但TRUNCATE 无事务且不触发trigger,有可能造成事故,故不建议在开发代码中使用此语句。
说明:TRUNCATETABLE 在功能上与不带WHERE 子句的DELETE 语句相同。
1. 【强制】在表查询中,一律不要使用* 作为查询的字段列表,需要哪些字段必须明确写明。
说明:1)增加查询分析器解析成本。2)增减字段容易与resultMap配置不一致。
2. 【强制】POJO类的boolean属性不能加is,而数据库字段必须加is_,要求在resultMap中进行字段与属性之间的映射。
说明:参见定义POJO类以及数据库字段定义规定,在sql.xml增加映射,是必须的。
3. 【强制】不要用resultClass当返回参数,即使所有类属性名与数据库字段一一对应,也需要定义;反过来,每一个表也必然有一个与之对应。
说明:配置映射关系,使字段与DO类解耦,方便维护。
4. 【强制】xml配置中参数注意使用:#{},#param#不要使用${} 此种方式容易出现SQL注入。
5. 【强制】iBATIS自带的queryForList(StringstatementName,int start,int size)不推荐使用。
说明:其实现方式是在数据库取到statementName对应的SQL语句的所有记录,再通过subList 取start,size的子集合,线上因为这个原因曾经出现过OOM。
正例:在sqlmap.xml中引入#start#, #size#
Map<String, Object> map = new HashMap<String,Object>(); map.put("start",start); map.put("size", size);
6. 【强制】不允许直接拿HashMap与HashTable作为查询结果集的输出。
反例:某同学为避免写一个<resultMap>,直接使用HashTable来接收数据库返回结果,结果出现日常是把bigint转成Long值,而线上由于数据库版本不一样,解析成BigInteger,导致线上问题。
7. 【强制】更新数据表记录时,必须同时更新记录对应的gmt_modified字段值为当前时间。
8. 【推荐】不要写一个大而全的数据更新接口,传入为POJO类,不管是不是自己的目标更新字段,都进行update table set c1=value1,c2=value2,c3=value3; 这是不对的。执行SQL时,尽量不要更新无改动的字段,一是易出错;二是效率低;三是binlog增加存储。
9. 【参考】@Transactional事务不要滥用。事务会影响数据库的QPS,另外使用事务的地方需要考虑各方面的回滚方案,包括缓存回滚、搜索引擎回滚、消息补偿、统计修正等。
10.【参考】<isEqual>中的compareValue是与属性值对比的常量,一般是数字,表示相等时带上此条件;<isNotEmpty>表示不为空且不为null时执行;<isNotNull>表示不为null值时执行。
1. 【推荐】图中默认上层依赖于下层,箭头关系表示可直接依赖,如:开放接口层可以依赖于
Web层,也可以直接依赖于Service层,依此类推:
• 开放接口层:可直接封装Service接口暴露成RPC接口;通过Web封装成http接口;网关控制层等。
• 终端显示层:各个端的模板渲染并执行显示层。当前主要是velocity渲染,JS渲染,JSP渲染,移动端展示层等。
• Web层:主要是对访问控制进行转发,各类基本参数校验,或者不复用的业务简单处理等。
• Service层:相对具体的业务逻辑服务层。
• Manager层:通用业务处理层,它有如下特征:
1) 对第三方平台封装的层,预处理返回结果及转化异常信息;
2) 对Service层通用能力的下沉,如缓存方案、中间件通用处理;
3) 与DAO层交互,对DAO的业务通用能力的封装。
• DAO层:数据访问层,与底层Mysql、Oracle、Hbase、OB进行数据交互。
• 外部接口或第三方平台:包括其它部门RPC开放接口,基础平台,其它公司的HTTP接口。
2. 【参考】(分层异常处理规约)在DAO层,产生的异常类型有很多,无法用细粒度异常进行
catch,使用catch(Exception e)方式,并throw newDaoException(e),不需要打印日志,
因为日志在Manager/Service层一定需要捕获并打到日志文件中去,如果同台服务器再打日志,浪费性能和存储。在Service层出现异常时,必须记录日志信息到磁盘,尽可能带上参数信息,相当于保护案发现场。如果Manager层与Service同机部署,日志方式与DAO层处理一致,如果是单独部署,则采用与Service一致的处理方式。Web层绝不应该继续往上抛异常,因为已经处于顶层,无继续处理异常的方式,如果意识到这个异常将导致页面无法正常渲染,那么就应该直接跳转到友好错误页面,尽量加上友好的错误提示信息。开放接口层要将异常处理成错误码和错误信息方式返回。
3. 【参考】分层领域模型规约:
• DO(Data Object):与数据库表结构一一对应,通过DAO层向上传输数据源对象。
• DTO(Data Transfer Object):数据传输对象,Service和Manager向外传输的对象。
• BO(Business Object):业务对象。可以由Service层输出的封装业务逻辑的对象。
• QUERY:数据查询对象,各层接收上层的查询请求。注:超过2个参数的查询封装,禁止使用Map类来传输。
• VO(View Object):显示层对象,通常是Web向模板渲染引擎层传输的对象。
1. 【强制】定义GAV遵从以下规则:
1) GroupID格式:com.{公司/BU }.业务线.[子业务线],最多4级。
说明:{公司/BU}例如:alibaba/taobao/tmall/aliexpress等BU一级;子业务线可选。
正例:com.taobao.tddl 或com.alibaba.sourcing.multilang
2) ArtifactID格式:产品线名-模块名。语义不重复不遗漏,先到仓库中心去查证一下。
正例:tc-client / uic-api / tair-tool
3) Version:详细规定参考下方。
2. 【强制】二方库版本号命名方式:主版本号.次版本号.修订号
1) 主版本号:当做了不兼容的API 修改,或者增加了能改变产品方向的新功能。
2) 次版本号:当做了向下兼容的功能性新增(新增类、接口等)。
3) 修订号:修复bug,没有修改方法签名的功能加强,保持API 兼容性。
3. 【强制】线上应用不要依赖SNAPSHOT版本(安全包除外);正式发布的类库必须使用RELEASE 版本号升级+1的方式,且版本号不允许覆盖升级,必须去中央仓库进行查证。
说明:不依赖SNAPSHOT版本是保证应用发布的幂等性。另外,也可以加快编译时的打包构建。
4. 【强制】二方库的新增或升级,保持除功能点之外的其它jar包仲裁结果不变。如果有改变,必须明确评估和验证,建议进行dependency:resolve前后信息比对,如果仲裁结果完全不一致,那么通过dependency:tree命令,找出差异点,进行<excludes>排除jar包。
5. 【强制】二方库里可以定义枚举类型,参数可以使用枚举类型,但是接口返回值不允许使用枚举类型或者包含枚举类型的POJO对象。
6. 【强制】依赖于一个二方库群时,必须定义一个统一版本变量,避免版本号不一致。
说明:依赖springframework-core,-context,-beans,它们都是同一个版本,可以定义一个变量来保存版本:${spring.version},定义依赖的时候,引用该版本。
7. 【强制】禁止在子项目的pom依赖中出现相同的GroupId,相同的ArtifactId,但是不同的
Version。
说明:在本地调试时会使用各子项目指定的版本号,但是合并成一个war,只能有一个版本号出现在最后的lib目录中。曾经出现过线下调试是正确的,发布到线上出故障的先例。
8. 【推荐】工具类二方库已经提供的,尽量不要在本应用中编程实现。
l json操作: fastjson
l md5操作:commons-codec
l 工具集合:Guava包
l 数组操作:ArrayUtils(org.apache.commons.lang3.ArrayUtils)
l 集合操作:CollectionUtils(org.apache.commons.collections4.CollectionUtils)
l 除上面以外还有NumberUtils、DateFormatUtils、DateUtils等优先使用org.apache.commons.lang3这个包下的,不要使用org.apache.commons.lang包下面的。原因是commons.lang这个包是从JDK1.2开始支持的所以很多1.5/1.6的特性是不支持的,例如:泛型。
9. 【推荐】所有pom文件中的依赖声明放在<dependencies>语句块中,所有版本仲裁放在
<dependencyManagement>语句块中。
说明:<dependencyManagement>里只是声明版本,并不实现引入,因此子项目需要显式的声明依赖,version和scope都读取自父pom。而<dependencies>所有声明在主pom的<dependencies > 里的依赖都会自动引入,并默认被所有的子项目继承。
10.【推荐】二方库尽量不要有配置项,最低限度不要再增加配置项。
11.【参考】为避免应用二方库的依赖冲突问题,二方库发布者应当遵循以下原则:
1) 精简可控原则。移除一切不必要的API和依赖,只包含Service API、必要的领域模型对象、Utils类、常量、枚举等。如果依赖其它二方库,尽量是provided引入,让二方库使用者去依赖具体版本号;无log具体实现,只依赖日志框架。
2) 稳定可追溯原则。每个版本的变化应该被记录,二方库由谁维护,源码在哪里,都需要能方便查到。除非用户主动升级版本,否则公共二方库的行为不应该发生变化。
1. 【推荐】高并发服务器建议调小TCP协议的time_wait超时时间。
说明:操作系统默认240秒后,才会关闭处于time_wait状态的连接,在高并发访问下,服务器端会因为处于time_wait的连接数太多,可能无法建立新的连接,所以需要在服务器上调小此等待值。
正例:在linux服务器上请通过变更/etc/sysctl.conf文件去修改该缺省值(秒): net.ipv4.tcp_fin_timeout = 30
2. 【推荐】调大服务器所支持的最大文件句柄数(File Descriptor,简写为fd)。
说明:主流操作系统的设计是将TCP/UDP连接采用与文件一样的方式去管理,即一个连接对应于一个fd。主流的linux服务器默认所支持最大fd数量为1024,当并发连接数很大时很容易因为fd不足而出现“open too many files”错误,导致新的连接无法建立。建议将linux 服务器所支持的最大句柄数调高数倍(与服务器的内存数量相关)。
3. 【推荐】给JVM设置-XX:+HeapDumpOnOutOfMemoryError参数,让JVM碰到OOM场景时输出dump 信息。
说明:OOM的发生是有概率的,甚至有规律地相隔数月才出现一例,出现时的现场信息对查错非常有价值。
4. 【参考】服务器内部重定向必须使用forward;外部重定向地址必须使用URL Broker生成,否则因线上采用HTTPS协议而导致浏览器提示“不安全”。此外,还会带来URL维护不一致的问题。
1. 【强制】可被用户直接访问的功能必须进行权限控制校验。说明:防止没有做权限控制就可随意访问、操作别人的数据,比如查看、修改别人的订单。
2. 【强制】用户敏感数据禁止直接展示,必须对展示数据脱敏。说明:支付宝中查看个人手机号码会显示成:158****9119,隐藏中间4位,防止隐私泄露。
3. 【强制】用户输入的SQL参数严格使用参数绑定或者METADATA字段值限定,防止SQL注入,禁止字符串拼接SQL访问数据库。
4. 【强制】用户请求传入的任何参数必须做有效性验证。说明:忽略参数校验可能导致:
l page size过大导致内存溢出
l 恶意order by导致数据库慢查询
l 正则输入源串拒绝服务ReDOS
l 任意重定向
l SQL注入
l Shell注入
l 反序列化注入
5. 【强制】禁止向HTML页面输出未经安全过滤或未正确转义的用户数据。
6. 【强制】表单、AJAX提交必须执行CSRF安全过滤。
说明:CSRF(Cross-siterequest forgery)跨站请求伪造是一类常见编程漏洞。对于存在CSRF
漏洞的应用/网站,攻击者可以事先构造好URL,只要受害者用户一访问,后台便在用户不知情情况下对数据库中用户参数进行相应修改。
7. 【强制】URL外部重定向传入的目标地址必须执行白名单过滤。
正例:
try{ if(com.alibaba.fasttext.sec.url.CheckSafeUrl
.getDefaultInstance().inWhiteList(targetUrl)){ response.sendRedirect(targetUrl);
}
} catch (IOException e){ logger.error("Check returnURL error! targetURL=" + targetURL,e); throwe;
8. 【强制】Web应用必须正确配置Robots文件,非SEO URL必须配置为禁止爬虫访问。
User-agent: * Disallow: /
9. 【强制】在使用平台资源,譬如短信、邮件、电话、下单、支付,必须实现正确的防重放限制,如数量限制、疲劳度控制、验证码校验,避免被滥刷、资损。
说明:如注册时发送验证码到手机,如果没有限制次数和频率,那么可以利用此功能骚扰到其它用户,并造成短信平台资源浪费。
10.【推荐】发贴、评论、发送即时消息等用户生成内容的场景必须实现防刷、文本内容违禁词过滤等风控策略。
建议下载官方的pdf格式更利于学习与阅读://www.VeVB.COm/books/592610.html