Recently, I have been studying Ali’s Java development manual, and now I have summarized and sorted out the most important and most easily ignored parts. If you need them, you can refer to them as follows:
First, naming style
-
1,(point 2 of the original text) all programming related naming is strictly prohibited to use pinyin and English mixed way, is strictly prohibited to use Chinese; Interpretation: This is to improve the readability of the code and avoid ambiguity;
-
2. (Point 5 of the original text) All constants are named in uppercase, and words are separated by underscores to express themselves as clearly as possible; Interpretation: To improve the readability of the code;
-
Pojo class Boolean variables, do not add is prefix, to avoid part of the framework parsing serialization errors;
-
4. (Point 9 of the original text) The package name must be lowercase and singular. There is only one English word between the ‘.’ delimiter. Interpretation: unified specification, improve readability, refer to spring naming method;
-
5,(point 11 of the original text) avoid completely non-standard abbreviations, the code should be self-explanatory, read the meaning;
-
6. If modules/interfaces/classes/methods use design patterns, they should be named to reflect the specific pattern. Interpretation: improve code readability and quickly understand specific design methods;
Second, constant definition
-
1. Disallow magic values (non-predefined constants) in code; Interpretation: if it is a constant, it must be defined in advance to avoid misuse of bugs;
-
2. Use uppercase ‘L’ after a value when assigning long or long.
Third, the code format
-
1. (point 5 of the original text) use 4 Spaces for indentation, prohibit the use of TAB key; Interpretation: indent format unified, improve code readability,idea code written directly Ctrl+Alt+L is finished
-
2. (Point 6 of the original text) The double slash of the comment has one and only one space with the content of the comment; Eg :// This is a sample annotation interpretation: unified format, improve code readability;
-
3. Line breaks are required if the number of characters in a single line exceeds 120;
-
4, IDE text file encoding is set to UTF-8, file newline format is Unix; Interpretation: Avoid character avoid error problem
-
5. The number of lines in a single method should not exceed 80 lines (including signature & braces & blank lines), and common logic should be extracted and reused; Interpretation: Improved code readability;
Four, OOP code
-
1,(point 3 of the original text) Variable parameters can be used only when the same parameter type and business meaning, do not use Object; Interpretation: Variable parametric programming is not recommended, as discussed in effective Java;
-
2. Don’t use outdated classes or methods. Interpretation: Obsolete classes and methods may hide bugs or efficiency issues;
-
Call equals using constants or objects that determine values. Interpretation: Avoid NPE;
-
4. All wrapper types are worth comparing using equals. Avoid value errors, such as Integer values (-128~127) are equal when using ‘==’, and other variables are not equal.
-
5. (Article 8 of the original text) Any monetary amount shall be stored in the smallest monetary unit and the integer type (e.g., renminbi cents); Interpretation: To avoid error in amounts, I think you can also use BigDecimal to calculate and store amounts, depending on the design;
-
6. Define DO class attributes to match database field types. Data overflow may occur if the database field type is BigINT and the attribute of DO is Integer.
-
7. It is forbidden to convert a double value into a BigDecimal object using the constructor BigDecimal(double); Interpretation: errors may occur due to loss of accuracy;
-
DO not set default attribute values when defining POJO classes such as DO, DTO, and VO. Interpretation: May cause field error update issues (fields that do not need or do not need to be updated are updated or assigned);
-
String concatenation of loop weights uses the Append method of StringBuilder. Interpretation: Avoid creating unnecessary objects to improve GC performance;
-
10. (Point 25 of the original text) Access control of class members and methods is as strict as possible; Interpretation: Avoid misuse, easy to decouple;
Five, date and time
-
1. When formatting dates, ‘YYYY’ is used when passing pattern to indicate the year. The semantics in the JDK are defined differently and errors can occur.
-
2, not allowed anywhere in the program :<1, java.sql.date; <2,java.sql.Time; <3,java.sql.Timestamp; I strongly recommend using java8’s date and time API when it comes to time/date calculations.
-
3. Use enumeration values instead of months. Eg: the JDK native Calendar. JANUARY; Interpretation: It is recommended to use enumeration to improve the maintainability of the program when dealing with data representing the scope.
Sixth, set processing
-
1. Whenever an object overrides hashcode, it must override equals; Interpretation: Avoid Set/Map data comparison or storage errors;
-
2, (3) in the use of Java. Util. Stream. The Collectors toMap method of a class into Map collections be sure to use contains the parameter type for BinaryOperator, parameter method, called mergeFunction otherwise throw Ille when the same key value galStateException; MergeFunction allows you to define a value that has the same key.
-
3, (4) in the use of Java. Util. Stream. The Collectors class toMap method to Map collections, it is important to note when the value is null will throw NPE;
-
The subList result of ArrayList cannot be forcibly converted to ArrayList, otherwise a ClassCastException will be thrown. SubList returns an internal class of The ArrayList, which is only a view of the ArrayList.
-
ToArray (T[] array); toArray(T[] array); toArray(T[] array); ToArray () returns an Object[] class. If toArray() is used, throw ClassCastException.
-
When using the addAll() method of any implementation class of the Collection interface, ensure that the input Collection parameter is not null; otherwise, NPE will be thrown.
-
7, 13 points (the original) using tools Arrays. The asList converts an array into collection, cannot use the modify the collection related methods, such as the add/remove operation will throw an UnsupportedOperationException exception; The result of asList is just an inner class of Arrays that does not implement collection modification methods.
-
Do not remove/add elements in a foreach loop. Remove elements should be Iterator. If they operate concurrently, lock the Iterator. Iterator is the standard way of iterating over a collection.
-
9. (Point 17 of the original text) When the set is initialized, specify the initial capacity; Interpretation: Avoid resource and performance loss caused by continuous expansion;
-
10. Use entrySet to traverse the Map collection, not keySet, or map. forEach if java8. Interpretation :entrySet is more efficient (traversal only once);
-
11. The ConcurrentHashMap key&Value cannot be null; TreeMap key cannot be null; otherwise, the NPE will be thrown.
Seven, concurrent processing
-
(1) Obtaining singletons must be thread-safe, and methods must be thread-safe; Interpretation: Singletons can be created and retrieved by hungry /DCL/ synchronous slackers, and thread safety is more important than the partial loss of performance;
-
Thread resources must be created by thread pool/Thread pool/Thread pool/thread pool/thread pool/thread pool. Avoid Executors. Interpretation: Reduces resource consumption caused by frequent creation and destruction of threads, while explicitly creating threads greatly improves readability and avoids the risk of resource exhaustion.
-
5. The SimpleDateFormat thread is not safe. Do not define it as static or concurrency issues may occur. Reading: java8 environment it is best to use a new date/time of the API, eg: LocalDate/LocalDateTime (thread safe and more friendly API);
-
4. In concurrent environments, custom ThreadLocal variables must be reclaimed. Otherwise, business logic may be affected and memory leaks may occur.
-
5. (Point 7 of the original text) Ensure that the lock sequence of multiple resources is consistent, otherwise deadlock problems may occur;
-
6,(point 9 of the original text) in the use of lock lock to pay strict attention to the location and method of lock, to prevent the occurrence of lock failure to unlock abnormal or lock failure to successfully release the lock resulting in deadlock; Interpretation: Correct locking posture:
-
7. Before attempting to acquire the lock, you must determine whether the lock is successful before processing the next logical step. Interpretation: If the attempt to acquire the lock fails without judgment, the following logic will cause an exception to be thrown when the lock is released.
-
8. (Point 11 of the original text) Simultaneous update of a record should be synchronized lock processing, lock in the application layer/cache/database/other levels, while considering performance problems, pay attention to the use of optimistic lock (access conflict probability less than 20%) or pessimistic lock selection;
-
9. When processing scheduled tasks simultaneously, ScheduledExecutorService is used instead of using Timer(any abnormal task may terminate all tasks).
-
When using CountDownLatch for synchronization control, each thread must ensure that the countDown method is executed before exiting. Avoid the main thread being unable to continue execution because it cannot execute await.
Control statement
-
Each case in the switch is either terminated with a continue, break, return, etc., or a comment indicating which case the program continues to execute, and must include a default statement at the end; Interpretation: Improve code readability, avoid bugs;
-
When the variable type in the switch parentheses is String and the variable is an external parameter, null must be used first; otherwise, NPE will occur.
-
3. (point 4) The ternary operator (condition? In expression 1: Expression 2), it is highly noted that expressions 1 and 2 May throw an NPE exception caused by automatic unpacking when the type is aligned.
-
4. Avoid using the “equal” judgment as an interrupt or exit condition in high-concurrency scenarios. Interpretation: There may be equivalent judgment breakdown problem;
-
5. Avoid unnecessary object creation/database connection /try-catch operations in the loop. Interpretation: Improve application performance;
-
6. Protect the interface input parameters for batch operations;
Ix. Annotated protocols
-
Classes, class attributes, and class methods must be annotated using the Javadoc specification in the /** content */ format. Interpretation: Improved code readability. Javadoc can also generate code comments.
-
2. All abstract methods (including those in the interface) must be annotated in Javadoc and must indicate what the method does and does, in addition to return values, parameters, and exception descriptions. Interpretation: Abstract method is actually exposed interface API, API must consider ease of use;
-
(4) A single line comment inside the method, with a new line above the commented statement, using // comment;
-
4. All enumerated type fields must have comments stating the purpose of each data item. Interpretation: Improve code readability;
Ten, other
-
1, when using regular expressions, make good use of their precompilation function, which will effectively speed up the matching of regular expressions. The results of Pattern.compile will be declared static final.
-
2, avoid using Apache Beanutils for attribute copy, poor performance;
-
3, background variables sent to the page must be added $! ${var} is the exclamation mark in the middle of {var}, otherwise var does not exist.
Finally attached download link: Java development manual Taishan edition, for reference;