This is the 24th day of my participation in Gwen Challenge

Naming style

  • The name of the classuseUpperCamelCaseStyle, except:
    • DO: Data Object. The Data source Object is transmitted up through the DAO layer in one-to-one correspondence with the database table structure
    • BO: Business Object. An object that encapsulates the business logic output by the Service layer
    • DTO: Data Transfer Object. The object that the Service or Manager transmits out
    • VO: View Object: displays the Object. Typically objects transferred from the Web to the template rendering engine layer
    • AO: Application Object. Abstract reusable object models between the Web layer and the Service layer
    • PO: POJO abbreviation,Plain Ordinary Java Object. DO,DTO,BO,VO, etc. DO not use xxxPOJO names
    • UID
  • The lowerCamelcase style is used for method names, parameter names, member variables, and local variables
  • Constant name all uppercase, words separated by underscores, and strive to semantic expression complete and clear, not too long name
  • Abstract class names start with Abstract or Base
  • Exception class names end with Exception
  • The Test class name must be the name of the class to be tested, ending with Test
  • A type is used next to a bracket to represent an array
  • POJO class Boolean variables should not be prefixed with is, which can cause serialization errors in some frameworks
  • Package names are all lowercase, with one and only one natural semantic English word between the dot delimiters. The package name must be singular. However, class names can be plural if they have plural meanings
  • Put an end to non-standard abbreviations and avoid looking at the text without meaning
  • To achieve code self-interpretation, any custom programming element is named using as complete a combination of words as possible to express meaning
  • When naming constants and variables, type nouns are placed at the end of words to improve identification
  • If modules, interfaces, classes, or methods use design patterns, they should be named to reflect the design pattern
  • Keep the code simple by not adding any modifiers (public) to the methods and properties of the interface classes
  • Try not to define variables in the interface; if you do define variables, they must be related to interface methods and are fundamental to the entire application
    • Interface method signature: void commit()
    • Interface base constant: String COMPANY=”Oxford”
  • Interfaces and implementation classes:
    • For Service and DAO classes, based on SOA concepts, the exposed Service must be the interface, and the internal implementation class is distinguished from the interface by the Impl suffix
    • If it is the name of the interface that describes ability, the corresponding adjective is interface (-able)
  • Enumeration class beltEnumSuffixes, enumerator names must be all uppercase
    • Enumerated classes are special classes whose field members are constant and whose constructors are enforced by default to be private
  • Naming conventions for each layer:
    • Service or DAO layer method naming conventions:
      • Methods that get individual objects are prefixed with get
      • Methods that get multiple objects are prefixed with list and end with a plural
      • Methods that get statistics are prefixed with count
      • Insert methods are prefixed with either save or insert
      • Delete methods are prefixed with remove or delete
      • The modified methods are prefixed with update
    • Naming conventions for domain models:
      • Data object: XxxDO,Xxx is the name of the data table
      • Data transfer object: XxxDTO,Xxx indicates the name related to the service domain
      • Display object: XxxVO, XXX is usually the name of the web page
      • POJO refers to DO,DTO,BO, and VO. DO not name it XxxPOJO

Constants defined

  • Do not allow any undefined constants in your code
  • When assigning long or long, use uppercase L after the value, not lowercase L. This is because lower case can be confused with the number 1
  • Don’t use a single constant class to maintain all constants
    • Large and complete constant classes are messy and can only be located using the lookup function to modify constants, which is not conducive to understanding and maintenance
  • There are five levels of constant reuse:
    • Shared constants across applications: Placed in a binary library, usually under the constant directory in client.jar
    • Application class shared constants are placed in a library, usually under the Constant directory in a submodule
    • The shared constants within the subproject are in the constant directory of the current subproject
    • Intra-package shared constants are in the constant directory of the current package
    • Intra-class shared constants are defined directly within a class private static final
  • If the value of a variable changes only within a fixed range, useenumThe type definition
    • If there are extended attributes other than the name, use enum types, such as seasons, indicating the number of seasons in a year:
public enum SeasonEnum {
	SPRING(1),SUMMER(2),AUTUMN(3),WINTER(4);
	private int seq;
	SeasonEnum(int seq) {
		this.seq=seq; }}Copy the code

Code format

  • Conventions for the use of braces:
    • If the braces are empty, write it succinctly as {} without a line break
    • If non-empty code block:
      • No line breaks before open braces
      • Newline after opening brace
      • Newline before closing brace
      • No line break if there’s else after the close brace
      • A close brace indicating termination must be followed by a line break
  • Conventions for the use of parentheses:
    • Do not place Spaces between the left parenthesis and the character
    • There should also be no Spaces between the closing brace and the character
    • Space is required before the opening brace
  • Reserved words such as if,for,while,switch,do, etc. must have Spaces between parentheses
  • Any binocular, ternary operator requires a space to the left and right
    • The operators include:
      • The assignment operator :=
      • Logical operator :&&
      • Sign of addition, subtraction, multiplication and division
  • Indent with 4 Spaces
  • There is one and only one space between the comment’s double slash and the comment’s content
  • When method arguments are defined and passed in, multiple argument commas must be followed by Spaces
  • The total number of lines for a single method should not exceed 80:
    • The total number of method signatures excluding comments, left and right braces, method code, empty lines, carriage returns, and any invisible characters must not exceed 80 lines
    • Code logic distinguishes red flowers from green leaves, personality from commonality:
      • Green leaf logic stands alone as an additional method to make the trunk code clearer
      • Common logic is extracted into common method, which is easy to reuse and maintain
  • You do not need to add more than one space to align the characters on one line with those on the previous line
  • Different logic, different semantics, different business code only need to insert a blank line split to improve readability

OPP statute

  • Avoid accessing a class’s static variables and methods through a class’s object reference, which increases the compiler’s parsing cost. Use the class name instead
  • All Override methods must have @override
  • Java variable parameters can be used only when the parameter types and service meanings are the same, instead of Object
    • Mutable arguments must be placed at the end of the argument list, and it is recommended that you do not program with mutable arguments as much as possible
  • Method signatures (method names and parameter lists) are not allowed to be modified for interfaces that are being invoked externally or that rely on libraries. Obsolete interfaces must be annotated with == @deprecated == and clearly state what new interfaces and services are being adopted
  • Cannot use obsolete classes or methods:
    • The provider of an interface is obligated to provide a new interface if it is clearly obsolete
    • As the caller, what is the obligation to verify the new implementation of an obsolete method
  • ObjecttheequalsMethod is prone to throw null-pointer exceptions and should be called using constants or objects that are determined to have valuesequals
    • “test”.equals(Object)
    • Java.util. Objects is recommended
  • All comparison of values between wrapped class objects of the same type is done using equals
    • For Integer var =? When assigning values in the range -128 to 127,Integer objects are generated in integercache. cache and reuse existing objects. Integer values in this range can be determined by using ==
    • However, all data outside this interval will be generated on the heap without reuse of existing objects, so using equals is recommended
  • Any monetary amount is stored in the smallest monetary unit and is of integer type
  • Equivalence judgment between floating point numbers:
    • Primitive types cannot be compared with ==
    • The package type cannot be usedequalsTo judge
      • Floating point numbers are encoded by mantissa + order code, similar to the representation of significant numbers + exponents in scientific notation. Binary cannot accurately represent most decimal numbers
    • To avoid problems, all floating point numbers are defined using BigDecimal
/* * Floating-point numbers of type float: * specifies a range of error within which two floating-point numbers are considered equal. */
 float a = 1.0 f - 0.9 f;
 float b = 0.9 f - 0.8 f;
 float diff = 1e - 6f;
 if (Math.abs(a-b) < diff) {
 	System.out.println("true");
 }

/* * Uses BigDecimal to define values, followed by the floating-point operation */
 BigDecimal a = new BigDecimal("1.0");
 BigDecimal b = new BigDecimal("0.9");
 BigDecimal c = new BigDecimal("0.8");
 BigDecimal x = a.substract(b); 
 BigDecimal y = b.substract(c);
 if (x.equals(y)) {
 	System.out.println("true");
 } 
Copy the code
  • When defining the data object DO class, the property type matches the database field type
    • The bigINT of the database field must correspond to the type of the class attribute Long
  • Constructors are disallowedBigDecimal(double)The way todoubleValues intoBigDecimalObject:
    • BigDecimal(Double) carries the risk of loss of precision, causing business logic exceptions in scenarios where exact calculations or value comparisons are performed
      • A constructor with an input of String is recommended
      • Or use the valueOf method of BigDecimal: this internally executes the toString of Double, truncating the mantras with the precision that can actually be expressed
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = BigDecimal.valueOf(0.1);
Copy the code
  • Standard for use of basic types and packaging types:
    • All POJO class attributes must use wrapper class data types
    • The return values and parameters of RPC methods must use wrapper data types
    • All local variables use primitive data types
  • When defining POJO classes like DO,DTO,VO, etc., DO not set any property defaults
  • The serialVersionUID field cannot be modified when a new attribute is added to a serialized class; otherwise, deserialization will fail. If the upgrade is completely incompatible to avoid deserialization chaos, you can change the serialVersionUID value. A serialization runtime exception is thrown if the serialVersionUID is inconsistent
  • Constructor disallows any business logic, and if there is any initialization logic, put it in init
  • POJOClass have to writetoStringMethod if it inherits aPOJOClass, which needs to be added firstsuper.toString
    • When a method throws an exception, you can call the toString() method of the POJO directly to print the property value for troubleshooting
  • A ban onPOJOClass, also exists corresponding to the property XxxisXxx()getXxx()methods
    • When the framework calls the fetch method of attribute Xxx, it is not certain which method must be called first
  • String index access using the split method to get the array, you need to do a final check whether content after the delimiter, otherwise there will be a IndexOutofBoundsException anomalies
  • When a class has more than one constructor, or more than one method with the same name, these methods should be placed together in order to be easy to read
  • Methods within a class are defined in the following order:
    • Public or protected methods
      • Public methods are the most frequently used methods by class callers or maintainers and are best shown first
      • Protecting methods, while required by subclasses, can also be a core method in the template design pattern
    • Private methods
      • The outside of a private method is generally a black box implementation that you don’t care about
    • Getter or setter methods
      • Getter or setter methods for all services and DAOs are placed at the end of the class
  • In setter methods, the parameter name is the same as the class member variable name,this. Member name = parameter name.
  • Do not add business logic to getter or setter methods
  • Loop body, string class concatenation mode, useStringBuildertheappendMethod to extend
    • This will result in a new StringBuilder object being created for each loop
    • Then append
    • Finally, the toString method returns a String object, resulting in a waste of resources
  • Final can be declaredClasses, member variables, methods, and local variables.When using final:
    • Classes that are not allowed to be inherited
      • String
    • The referenced domain object that is not allowed to be modified
    • Methods that are not allowed to be overridden
      • Setter methods in poJOs
    • Local variables that do not allow reassignment during run time
    • Avoid repeating a variable in context, and use final descriptions to force redefinitions for better refactoring
  • Don’t useObjectthecloneMethod copy object:
    • The clone method of the object is shallow copy by default
    • If you want to achieve deep copy, you need to rewrite the Clone method to achieve deep traversal copy of domain objects
  • Class member and method access control protocol:
    • The constructor must be private if the object is not allowed to be created directly from the outside via new
    • Utility classes are not allowed to have public or default constructors
    • Class non-static member variables that are shared with child members must be protected
    • Class member variables that are non-static and used only in this class must be private
    • Class static member variables must be private if they are used only in this class
    • For static member variables, consider whether they are final
    • Class member methods must be private if they are called only from within the class
    • Limit the use of protected when class member methods are only exposed to inherited classes

Date/time

  • Date formatting when passed inpatternIs lowercase for the yearyyyy
    • Date formatting:
      • Yyyy Indicates the year of the current day
      • YYYY Indicates the year of the week of the day. A week starts on Sunday and ends on Saturday. If the New Year occurs this week, the year YYYY is the following year
  • Distinguish between uppercase M and lowercase M, uppercase H and lowercase H in date format:
    • The month is a capital M
    • The minute is a lowercase m
    • 24 hours is capital H
    • 12 hours is a lowercase H
  • Gets the current number of milliseconds:System.currentTimeMillis()
    • To get more precise nanosecond time values, use system.nanotime ()
    • Instant is recommended for time statistics scenarios
  • Do not use the relevant time methods in java.sql
  • Do not write 365 as the year of death in the program, to avoid date conversion errors or program logic errors in the Gregorian calendar leap year
    • Use the LocalDate method
// Get the number of days this year
int daysOfThisYear = LocalDate.now().lengthOfYear();

// Gets the number of days in a specified year
LocalDate.of(2011.1.1).lengthOfYear();
Copy the code
  • Use enumerated values in the Calendar to refer to months
    • If you are using numbers, note that the month of Date,Calendar, and other date-related classes ranges from 0 to 11

Set processing

  • Handle hashCode and equals:
    • Whenever you override equals, you have to override hashCode
    • A Set stores unique objects according to hashCode and equals, so objects stored in a Set must override those two methods
    • If a custom object is used as a Map key, it must be overriddenhashCodeandequals
      • String overrides the hashCode and equals methods so that String objects can be used as keys
  • The subList result of ArrayList must not be forcibly converted to ArrayList, or ClassCastException will be thrown:
    • SubList returns the inner class subList of ArrayList, not ArrayList, but a view of ArrayList. All operations on SubList sublists are eventually reflected on the original list
  • In the subList scene, must pay attention to the add or remove elements of the original collection, will cause the child list traversal, add and remove ConcurrentModificationException anomalies
  • useMapMethod:
    • keySet()
    • values()
    • entrySet()
    • Return collection objects, you can’t add elements of the operation, otherwise it will throw an UnsupportedOperationException anomalies
  • Objects returned by the Collections class cannot be added or deleted:
    • If the query results in nothing, the empty Collection object collection.emptyList () is returned. Once the caller has carried on the add elements operation, will trigger UnsupportedOperationException anomalies
  • To use the collection to array method, you must use the collectiontoArrary(T[] array),I’m passing in an array of exactly the same type, and the size of the array islist.size()
    • If the array space allocated by the toArray parameter method is not large enough, the toArray method internally reallocates the memory space and returns the address of the new array.
    • If the number of elements in the array is greater than required, the array elements with subscript [list.size()] are set to NULL, and the rest of the array elements are left unchanged
    • Therefore, it is best to define the size of the method into the parameter group as consistent with the number of elements in the collection
List<String> list = new ArrayList<>();
list.add("guan");
list.add("bao");
String[] array = new String[list.size];
array = list.toArray(array);
Copy the code
  • When using the addAll() method of any implementation class of the Collection interface, an NPE judgment is made on the input Collection parameters
  • When you use the arrays.asList () utility class to convert an array to a collection, you can’t use the associated methods to modify the collectionadd, remove, clearMethod throwsUnsupportedOperationExceptionabnormal
    • The return object of asList is an Array inner class that doesn’t implement collection modification methods
    • Arrays.aslist is an adaptor pattern, but the data is still an array
  • Generic wildcard<? extends T>To receive the returned data. The generic collection written in this way cannot be usedaddmethods; <? super T>You can’t usegetMethod will fail when calling assignment as an interface
    • PECS(Producer Extends Consumer Super)
      • Read out frequently and use <? extends T>
      • For frequent insertions, use <? super T>
  • Don’t inforeachThe element in the loopremoveoraddoperation
    • Remove elements use the Iterator method, or lock the Iterator object if the operation is concurrent
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
	String item = iterator.next();
	if(condition) { iterator.remove(); }}Copy the code
  • inJDK 7In later versions,ComparatorThe implementation must satisfy three conditions, otherwiseArrays.sort, Collections.sortThere will be aIllegalArgumentExceptionException:
    • The comparison of x and y is the opposite of the comparison of y and x
    • X > y, y > z, x > z
    • If x = y, the comparison between x and z is the same as the comparison between y and z
  • In later versions of the JDK 7, generics for collections are defined using shorthand, that is, using <> directly to specify previously specified types
  • When the collection is initialized, specifies the collection initial value size
    • HashMap Is initialized using HashMap(int initialCapacity)
    • InitalCapacity = (Number of elements to be stored/load factor) + 1. Note that the default load factor (loader factor) is 0.75. If you cannot determine the initial size, set the default value to 16
  • useentrySettraverseMapSet of classeskv,Instead of usingkeySetMethod for traversal
    • If you are usingkeySetIn fact, it is traversed twice:
      • Convert to an Iterator object once
      • Fetch the value of the key from the hashMap once
    • EntrySet is more efficient by simply iterating once and putting both keys and values into the entry
    • For versions later than JDK 8, use the map.foreach method
    • Example:
      • Values () returns a collection of V values, which is a list collection object
      • KeySet () returns a Set of K values, which is a Set object
      • EntrySet () returns a collection of combinations of k-V values
  • Note that the Map class can store null values in k-v:
Collection classes Key Value Super instructions
Hashtable Null is not allowed Null is not allowed Dictionary Thread safety
ConcurrentHashMap Null is not allowed Null is not allowed AbstractMap Lock section technique
TreeMap Null is not allowed Allow null AbstractMap Thread insecurity
HashMap Allow null Allow null AbstractMap Thread insecurity
ConcurrentHashMap can be used to insert null values due to interference with HashMap, which will throw NPE exceptions
  • Rational use of the ordered form of the set– sortAnd stability of the set– order,Avoid the negative effects of disordered – unsort and unstable – unorder sets
    • Orderliness refers to the order in which the results of traversal are arranged according to some comparison rule
    • Stability means that the order of elements in each iteration of the set is constant
    • ArrayList, HashMap, TreeSet
  • Using the unique properties of the Set element, a Set can be quickly de-duplicated
    • Avoid using the contains method of List for traversal, comparison, and deduplication

Concurrent processing

  • Getting a singleton needs to be thread-safe, and the methods in it need to be thread-safe
    • Resource-driven classes, utility classes, and singleton factory classes all need attention
  • Specify meaningful thread names when creating threads or thread pools to facilitate backtracking in case of errors
  • Thread resources must be provided through thread pools, and explicit creation of threads in the application is not allowed
    • The benefit of using thread pools is to reduce the time spent creating and destroying threads, as well as the overhead of system resources, and solve the resource shortage problem
    • If you don’t use thread pools, you can run out of memory or overswitch by creating a large number of similar threads
  • Thread pools are not allowedExecutorsTo create, go throughThreadPoolExecutorsCreate a thread pool, so that people can be more clear about the running rules, avoid the risk of resource consumption
    • The following problems occur on the thread pool object:
      • FixedThreadPool and SingleThreadPool:
        • The allowed queue length is integer. MAX_VALUE, which may cause a large number of requests and result in OOM
      • CachedThreadPool and ScheduledThreadPool:
        • The number of threads allowed to be created is integer. MAX_VALUE, which may cause a large number of threads to be created, resulting in OOM
  • SimpleDateFormatIs a thread-unsafe class, do not define asstaticIf you define static, you must lock it or use the DateUtils utility class
    • Note thread safety. With DateUtils, you can do the following:
    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
    	@Override
    	protected DateFormat initialValue(a) {
    		return new SimpleDateFormat("yyyy-MM-dd"); }}Copy the code
    • In JDK 8, you can use:
      • Instant instead of the Date
      • LocalDateTime instead of Calendar
      • Instead of a SimpleDateFormat DateTimeFormatter
  • Custom ThreadLocal variables must be reclaimed:
    • Especially in the thread pool scenario, threads are often reused, and if custom ThreadLocal variables are not cleaned up, subsequent business logic and memory leaks can occur
    • Try to use try-finally blocks in proxies for recycling
ObjectThreadLocal.set(userInfo);
try{... }finally {
	ObjectThreadLocal.remove();
} 
Copy the code
  • For high concurrency, synchronous calls should consider the performance cost of locking.
    • If you can use lock-free data structures, don’t use locks
    • If you can lock blocks, don’t lock the whole method body
    • If you can use object locks, don’t use class locks
      • Keep the work of locking code blocks as small as possible and avoid calling RPC methods in locking code blocks
  • When multiple resources, database tables, and objects are locked at the same time, ensure that the lock sequence is consistent; otherwise, deadlock may occur
    • If thread 1 needs to lock A, B, and C in sequence, the update operation can be performed
    • Thread 2 must also be locked in the order of A, B, and C. Otherwise A deadlock may occur
  • In using blocking wait to acquire locks:
    • Must be outside the try block
      • If the lock method within the try block, throw an exception may be due to other methods, resulting in the finally block of code to unlock the unlock unlocked object, is called AQS tryRelease method, throw IlleagalMonitorStateException anomalies
    • There must be no method calls between the lock method and the try block that could throw an exception to avoid being unlocked in finally after a successful lock
      • If a method call between the lock method and the try block throws an exception, the lock cannot be unlocked, preventing other threads from acquiring the lock
    • In the Lock object Lock method may throw unchecked exceptions, lead to unlock to unlock, unlocked object will invoke AQS tryRelease method, throw IlleagalMonitorStateException anomalies
Lock lock = new XxxLock();
lock.lock();
try{... }finally {
	lock.unlock();
}
Copy the code
  • In the way the lock is acquired using the try mechanism:
    • Before entering the business code, you must determine whether the current thread holds the lock
    • The lock is released in the same way as the lock blocks wait
      • Unlock the Lock object method, when executed will call AQS tryRelease method, if the current thread holds a Lock, it throws IllegalMonitorStateException anomalies
Lock lock = new XxxLock();
boolean isLocked = lock.tryLock();
if (isLocked) {
	try{... }finally{ lock.unlock(); }}Copy the code
  • When modifying the same record concurrently, avoid update loss and lock:
    • Lock the application layer
    • Lock the cache
    • Add a lock to the database
    • Use version as the update basis
      • Optimistic locking is recommended if the probability of each access is less than 20%
      • Otherwise, use pessimistic locks
      • The number of optimistic lock retries must be at least three
  • When multithreading processes timed tasks in parallel:
    • When a Timer runs multiple TimerTasks and one of them does not catch a thrown exception, the task is automatically terminated
    • This problem is not present with ScheduleExecutorService
  • Pessimistic lock follows the principle of one lock two, three update and four release
  • useCountDownLatchPerform the asynchronous to synchronous operation:
    • The countDown method must be called before each thread exits
    • The thread executing code notices the catch exception and makes sure the counDown method is executed
    • Avoid the main thread failing to execute to await method until time out
      • An exception stack thrown by a child thread that cannot get an exception on the main try-catch thread
  • avoidRandomInstances are used by multiple threads, and sharing the instance is thread-safe, but can result in the same raceseedPerformance degradation
    • The Random instances:
      • Java. Util. Random instances
      • Math. The random ()
    • After JDK 7, ThreadLoalRandom can be used directly
  • In concurrent scenarios, through double-checked locksdouble-check lockingImplement delayed initialization to optimize potential problems:
    • Declare the target attribute as volatile
  • volatileUsed to solve the problem of multi-threaded memory invisible:
    • For one write read, can solve the variable synchronization problem
    • There is no solution to the thread-safety problem with multiple writes
    • For the count++ operation, use the following class implementation:
    AtomicInteger count = new AtomicInteger();
    count.addAndGet(1);
    Copy the code
    • After JDK 8, the LongAdder object is recommended for better performance than AtomicLong because it reduces the number of optimistic lock retries
  • If a HashMap fails to resize, the CPU will increase due to a deadlock caused by high concurrency:
    • Use other data structures
    • lock
  • ThreadLocalUnable to resolve shared object update problems, recommended usestaticTo modify:
    • This variable is shared by all operations within a thread
    • Therefore, it is set to a static variable, which is shared by all such instances
    • That is, the variable is loaded the first time the class is used, allocating only one piece of memory, as long as all the class objects defined in the thread can manipulate the variable

Control statements

  • Within a switch block:
    • Each case is terminated by a break or return
    • Or comments indicating which case the program will continue to execute until
    • A default statement must be included and placed at the end, even if the code is empty
  • When the variable inside the Switch parentheses is of type String and the variable is an external parameter, null judgment must be performed
  • Braces must be used in if, else, for, while, and DO statements, even if there is only one line of code. Avoid single-line encoding
  • Ternary operators:condition ? Expression 1: expression 2Note that expressions 1 and 2 May be unpacked when type alignment occursNPEabnormal
    • Trigger type aligned unpacking operation:
      • Expression 1 or expression 2 has only one primitive type
      • If expression 1 or expression 2 is not of the same type, unboxing will be forced to upgrade to the larger type
  • Avoid this in high-concurrency scenarios“Equal”Judge as a condition to interrupt or exit
    • Because if concurrency control is not handled well, it is easy to produce equivalence judgment “breakdown”. Use greater than or less than interval judgment conditions instead
    • Example: When determining that the remaining number is equal to 0, when the number is equal to 0, the number suddenly becomes negative due to a concurrent processing error, in which case, the processing cannot be terminated
  • When expressing exception branches, do not use if-else; rewrite to
if (condition) {
	...
	return obj;
}
// Then write the else business processing logic
Copy the code

For more than 3 layers of if-else logic determination code can be implemented using guard statements, policy mode, state mode, etc

  • In addition to the usual method:getXxx, isXxxDo not execute complex statements in conditional judgments. Assign the result of complex logical judgments to a meaningful Boolean variable name to improve readability
    • The logic inside many if statements is quite complex, and you need to analyze the final result of the expression to figure out what conditions to execute what statements
  • Do not insert assignment statements in other expressions (especially conditional expressions)
  • For performance considerations, the following operations are moved to the outside of the loop as far as possible:
    • Define objects, variables
    • Getting a database connection
    • Perform an unnecessary try-catch operation (consider whether the try-catch operation can be moved out of circulation)
  • Avoid using antilogic operators
    • Taking antilogical operators is not conducive to quick understanding
    • There must be a corresponding positive logical way to take the inverse logical way
  • Interface input parameter protection: In this scenario, interfaces are commonly used for batch operations
  • Parameter verification:
    • Need to beThe situation of parameter verification:
      • Methods that are called infrequently
      • Methods that are time-consuming to execute
        • In this case, the time of parameter verification is almost negligible
        • However, if the intermediate execution is returned due to parameter error, or error, the loss is not worth the gain
      • Methods that require extremely high stability and availability
      • Provide open interface, whether RPC, API, HTTP interface
      • Sensitive access
    • Don’t needThe situation of parameter verification:
      • A method that is most likely to be called through a loop. However, inspection requirements for external parameters must be indicated in the method specification
      • The underlying method that is called more frequently
      • Methods that are declared private and only called by their own code. If you can be sure that the incoming arguments from the code calling the method have already been checked or that there is no problem, you can leave the parameters unchecked

Annotation specifications

  • Class, class attributes, and class methods must be annotated using the Javadoc specification in the /** XXX */ format. // XXX is not allowed
  • All abstract methods, including those in interfaces, must use Javadoc annotations that, in addition to return values, parameters, and exception descriptions, must indicate what the method does and implements. The implementation requirements for subclasses and the considerations for invocation need to be explained
  • All classes must have a creator and creation date added
  • Method internal comment:
    • Single-line comment: Start a new line above the commented statement with a // comment
    • Multi-line comments: Use /* */ comments to align with the code
  • All enumerated type fields must have comments describing the purpose of each data item
  • When the level is high enough, English annotations should be used. Otherwise, make it clear in Chinese, as long as you keep the proper nouns and keywords in English
  • As code changes, comments should also be modified, especially parameters, return values, exceptions, core logic, etc. Keep your code in sync with comment updates
  • Comment code carefully:
    • Annotated code is explained in detail, not simply commented
    • If it is useless, it should be deleted
  • Requirements for notes:
    • Accurately reflect design ideas and code logic
    • Able to describe business implications and quickly understand the information behind the code
  • Good naming, code structure is self-explanatory, and comments ensure concise, accurate, and accurate expression
  • Special annotation mark, need to indicate the marking person and marking time. Pay attention to timely processing of these tags and frequent cleaning of such tags through tag scans. Online failures sometimes result from code at these markers
    • todoTODO: (mark person, mark time, [pretreatment time])
      • Represents functionality that is intended to be implemented, but is not yet implemented. This is actually a Javadoc tag. Applies only to classes, interfaces, methods
    • Error, does not workFIXME: (Mark person, mark time, [preprocessing time])
      • Using FIXME to mark a piece of code in comments is wrong and does not work and needs to be corrected in time

Before and after the separation

  • The API for the front and back end interaction needs to be clearProtocol, Domain name, path, request method, request content, status code, response body:
    • Protocol: The production environment must use HTTPS
    • Path:eachAPIThere needs to be a path, representsAPISpecific request address
      • It can only be a noun, plural is recommended, not a verb, because the request method already expresses the meaning of the action
      • The URL path cannot be capitalized. If words need to be separated, use underscores (_)
      • The path cannot carry the suffix “.json” or “.xml” of the request content type, expressed in the accept header
    • Request method:Definition of a specific operation
      • GET: retrieve
      • POST: the new
      • PUT: modify
      • DELETE: DELETE
    • Request content:
      • The parameters of the URL must have no sensitive information or meet security requirements
      • Content-type must be set if the body parameter is included
    • Response body: The response body can place multiple data types, as determined by the Content-Type header
  • Returns an empty array [] or an empty collection {} if the interface associated with the front and back data lists is empty.
  • When a server error occurs, the response information returned to the front end must containHTTP status code, errorCode, errorMessage, user prompt messageFour parts:
    • HTTP status code:The browser
      • 200 OK: indicates that the request is successfully completed and the requested resource is sent to the client
      • 401 Unauthorized: Requests require authentication, usually when a user does not log in
      • 403 Forbidden: The server rejects requests, usually for confidential information or duplicates other login users’ links to access the server
      • 404 Not Found: The server could Not reach the requested page. The requested resource does not exist
      • 500 Internal Server Error: indicates an Internal Server Error
    • ErrorCode: Front-end development
    • ErrorMessage: error checker
    • User information: User. The prompt must be short, clear, and friendly. Guide the user to the next step or explain the cause of the error
  • ErrorMessage is the embodiment of the front and back end error tracking mechanism. It can be output in the front end to the text control type=”hidden” or the user’s log, which can quickly locate the problem
  • The server uses oversized integers in all scenariosStringString return type. This parameter is disabledLongtype
    • JavaIf the server directly returnsLongInteger data to the front end,JSWill automatically convert toNumberType:
      • Number: a Double precision floating point Number. The principle and value range are the same as Double in Java
      • Long:The maximum value of the representation is zero2 ^ ^ 631. Over2 ^ ^ 53 (9007199254740992).The value of is converted toJStheNumber, some values will have precision loss
        • Within the value range of Long, there is absolutely no precision loss for any exponential integer of 2, so precision loss is a probability problem
        • A floating-point number can accurately represent any integer if the mantissa and exponent bits have unlimited space. But a double – precision floating – point number has only 52 mantissa bits
    • Example: Usually when the order number or transaction number is greater than or equal to 16 digits, there is a high probability of inconsistency between the two end documents. For example, the back-end is 362909601374617692 to the front-end is 362909601374617660
  • HTTPRequest byURLWhen passing parameters, the value cannot exceed2048Bytes:
    • The maximum length limit for urls varies slightly between browsers, and the logic for handling anything beyond the maximum length varies. 2048 bytes is the minimum for all browsers
  • HTTPRequest bybodyWhen passing content, you must control the length. After the maximum length, the backend parsing will fail:
    • The default limit for Nginx is 1MB
    • Tomcat’s default limit is 2MB
    • You can increase the limit on the server when services need to transmit large amounts of content
  • In paging scenarios, if the user input parameter is less than 1, the front end returns the first page parameter to the back end. If the parameter entered by the user is larger than the total number of pages, the backend returns to the last page
  • The internal redirection must be forward. The external redirection address must be generated by the URL unified proxy module. Otherwise, the browser displays an “unsafe” message because HTTPS is used online, and URL maintenance is inconsistent
  • The information returned by the server must be marked as cacheable, and if cached, the client may reuse the results of previous requests
    • Caching helps reduce the number of interactions and the average latency of interactions
    • Example: The HTTP 1.1In the,s-maxageNotifies the server to cache in seconds:
      • response.setHeader(“Cache-Control”, “s-maxage=” + cacheSeconds)
  • The data returned by the server is usedJSONFormat rather thanXML :
    • HTTP supports the use of different output formats, such as plain text,JSON,CSV,XML,RSS and HTML
    • When using user-oriented services, you should chooseJSONA standard data exchange format used in communication, including request and response
      • Application /JSON is a general-purpose MIME type that is practical, compact, and easy to read
  • The time format of the front and rear ends is YYYY-MM-DD HH: MM: SS and GMT

Other note

  • When using regular expressions, precompilation can effectively speed up regular matching
  • Do not define in the method body
  • Enumerated types can be defined in a binary library, and enumerated types can be used for parameters, but the interface return value is not allowed to use enumerated types or POJO objects containing enumerated types
  • When velocity calls an attribute of a POJO class, the template engine automatically calls getXxx() of the POJO class. If the POJO is a Boolean basic type variable, the template engine automatically calls isXxx. If it is a Boolean wrapper class object, the getXxx() method is called first
  • Backend to page variables must be added with $! {var}, notice the exclamation mark in the middle
    • If var is null or does not exist, ${var} is displayed directly on the desktop
  • Pay attention toMath.random()This method returns 0doubleType: specifies the value range0 <= x <1(Can take the value of zero, notice the division of zero)
    • If you get a Random number of integer type, you don’t need to enlarge x by several times 10 and then round it. You can use the nextInt or nextLong method of Random object directly
  • Gets the current number of secondsSystem.currentTimeMillis(),Instead of using new Date().getTime()
    • To get more precise nanosecond time values, use system.nanotime ()
    • After JDK 8, you need Instant for common situations such as statistics time
  • Don’t add any complex logic to the view template. According to MVC theory, the view’s job is to present, not code logic for the model and controller
  • Any data structure should be constructed and initialized to a specified size so that the data structure does not grow indefinitely and eat up memory
  • Clean up code snippets or configuration information that is no longer in use
    • For junk code or outdated configuration, resolutely clean up, to avoid excessive bloated programs and code redundancy
    • For code snippets that have been commented out temporarily and may be restored later, there is a uniform rule to use three slashes above the commented code to explain the reason for looking at the code