OOP code

  1. Avoid using a class’s object reference to access static variables or methods of that class, which unnecessarily increases compiler resolution costs.

  2. All Override methods must be annotated with @override.

Description: getObject() and get0bject() problems. One is the letter O, the other is the number 0, plus @override can accurately determine whether the Override is successful. In addition, if you change a method signature in an abstract class, the implementation class will compile an error immediately.

  1. "Mandatory"Only the same parameter type and service meaning can be used, instead of Object.

Note: Variable arguments must be placed at the end of the argument list. (Students are encouraged not to use variable parameter programming.)

Public List listUsers(String type, Long… ids) {… }

  1. [Mandatory] It is not allowed to modify the method signature of the interface that is being called externally or the interface that the library depends on to avoid impact on the interface caller. Obsolete interfaces must be annotated with @deprecated and clearly state what the new interface or service is being adopted.

  2. [Mandatory] Do not use obsolete classes or methods.

Java.net.URLDecoder method decode(String encodeStr) this method is outdated, should use a double parameter decode(String source, String encode). An interface provider is obliged to provide a new interface if it is clearly an outdated interface. It is incumbent on the caller to verify what the new implementation of the obsolete method is.

  1. "Mandatory"Object’s equals method is prone to null-pointer exceptions and should be called using constants or objects with determined values.

Is: “test”. The equals (object);

Example: the object. The equals (” test “);

Note: Java.util.objects #equals (a utility class introduced in JDK7) is recommended.

  1. "Mandatory"Comparison of values between all of the integer wrapped class objects, using the Equals method.

Note: For Integer var =? For values between -128 and 127, Integer objects are generated in integercache. cache and reuse existing objects. Integer values in this range can be determined directly by using ==, but all data outside this range will be generated on the heap. It does not reuse existing objects, which is a big pit and is recommended to use equals.

  1. [Mandatory] Any monetary amount is stored in the smallest monetary unit and is of integer type.

  2. [Mandatory] Equals between floating-point numbers. Base data types cannot be compared with equals. Wrapper data types cannot be compared with equals.

Note: Floating point number adopts the encoding mode of “mantissa + order code”, which is similar to the representation mode of “significant number + exponent” of scientific counting method. Binary cannot accurately represent most decimal fractions, refer to code Efficiency for details.

Example:

Float a = 1.0f – 0.9f; float a = 1.0f – 0.9f;

Float b = 0.9f – 0.8f; float b = 0.9f – 0.9f;

if (a == b) {

// Expect to enter this code quickly to execute other business logic

// But in fact a==b is false

}

Float x = Float.valueOf(a);

Float y = Float.valueOf(b);

if (x.equals(y)) {

// Expect to enter this code quickly to execute other business logic

// The result of equals is false

}

Is:

(1) Specify an error range within which the differences of 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");

}
Copy the code

(2) Use BigDecimal to define values and then perform floating-point operations.

BigDecimal a = new BigDecimal("1.0");

BigDecimal b = new BigDecimal("0.9");

BigDecimal c = new BigDecimal("0.8");

BigDecimal x = a.subtract(b);

BigDecimal y = b.subtract(c);

if (x.equals(y)) {

	System.out.println("true");

}
Copy the code

10. [Mandatory] When defining the data object DO class, the attribute type must match the database field type.

Example: BIGInt of a database field must correspond to Long of a class attribute.

Counterexample: In a case, the database table ID field definition type bigInt unsigned, the actual class object property is Integer, with the id increasing

Larger, the representation range of Integer is exceeded and overflow becomes negative.

11. [Enforce] Disallow the use of the constructor BigDecimal(double) to convert a double value to a BigDecimal object.

Note: BigDecimal(Double) carries the risk of loss of accuracy and can cause business logic exceptions in scenarios where exact calculations or value comparisons are performed.

For example: BigDecimal g = new BigDecimal(0.1f); The actual value is 0.10000000149

Positive example: Preferentially recommend a constructor that takes a String argument, or uses the valueOf method of BigDecimal, which actually executes internally

The toString of Double, which truncates the mantissa to the precision that Double can actually express it.


BigDecimal recommend1 = new BigDecimal("0.1");

BigDecimal recommend2 = BigDecimal.valueOf(0.1);
Copy the code

12. Criteria for the use of basic data types and wrapper data types are as follows:

1) [Mandatory] All POJO class attributes must use wrapper data types.

The return values and parameters of RPC methods must use wrapper data types.

3) [Recommendation] Use basic data types for all local variables.

Note: The absence of initial values for POJO class attributes reminds users that they must explicitly assign values when they need to use them. Any NPE problems, or entry checks, are guaranteed by the user.

Example: The query result of the database may be null because of automatic unpacking and NPE risk of receiving with basic data type.

Counterexample: the transaction report of a certain business shows the rise and fall of the total transaction amount, namely, plus or minus X %. X is the basic data type and the RPC service is called. When the call fails, the default value is returned and the page displays 0%, which is unreasonable and should be displayed as a dash -. So the null value of the wrapper data type can indicate additional information, such as: remote call failure, abnormal exit.

13. [Mandatory] DO not set any default values when defining POJO classes such as DO, DTO, and VO.

Counterexample: The POJO class createTime defaults to new Date(), but this property is not put in when the data is extracted, and is updated with other fields, causing the creation time to be changed to the current time.

14. [Mandatory] Do not modify the serialVersionUID field when serializing new attributes of the class to avoid anti-sequence failure; Change the serialVersionUID value if the upgrade is completely incompatible to avoid deserialization clutter.

Note: Note that inconsistent serialVersionUID throws a serialization runtime exception.

15. [mandatory] Do not add any business logic to constructor. If there is any initialization logic, put it in init method.

The POJO class must write toString. If you inherit another POJO class using the tools in the IDE: Source > generate toString, note that super.tostring is added in front of it.

Note: When a method executes an exception, you can directly call the toString() method of the POJO to print its attribute value for easy troubleshooting.

17. [Mandatory] Prohibit the existence of isXxx() and getXxx() methods corresponding to property XXX in POJO classes.

Note: When the framework calls the extract method of property XXX, it is not certain which method is the first one to be called.

18. “recommended” String index access using the split method to get the array, to do the last check whether content after the delimiter, otherwise there will be a risk of IndexOutOfBoundsException.

Description:

String str = “a,b,c,,”;

String[] ary = str.split(“,”);

// Expect more than 3, result is 3

System.out.println(ary.length);

19. When a class has multiple constructors, or methods with the same name, these methods should be placed together in order to be easy to read, with this rule taking precedence over the next one.

20. The order in which methods are defined within a class is public or protected > private > getter/setter.

Description: Public methods are the most concerned methods of class callers and maintainers, the best first screen display; The protection method, though only a subclass concern, may also be the core method in the “template design pattern”; The outside of a private method is usually a black-box implementation that doesn’t need special attention; Getter /setter methods for all services and DAOs are placed at the end of the class body because the information carried is of low value.

21. 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 your getter/setter methods to make troubleshooting difficult.

Example:

public Integer getData (a) {

	if (condition) {
	
		return this.data + 100; 
	
	} else {
	
		return this.data - 100; }}Copy the code

22. The string concatenation method in the loop is extended using the Append method of StringBuilder.

Note: In the following example, the decomcompiled bytecode file shows that each loop will new a StringBuilder object and append it

The toString method is used to return a String object, wasting memory resources.

Example:

String str = "start";
for (int i = 0; i < 100; i++) {
    str = str + "hello"; 
}
Copy the code

23. The final keyword can be used to declare classes, member variables, methods, and local variables:

1) Classes that are not allowed to be inherited, such as String.

2) It is not allowed to modify referenced domain objects, such as POJO class domain variables.

3) Methods that are not allowed to be overridden, such as setter methods of POJO classes.

4) Local variables that are reassigned during runtime are not allowed.

5) Avoid the repeated use of a variable in context. Using final forces a variable to be redefined for better refactoring.

24. [Recommendation] Carefully copy objects using the Clone method of Object.

Note: The clone method is shallow copy by default. If you want to achieve deep copy, you need to overwrite the Clone method to achieve deep traversal copy of domain objects.

25. [Recommended] Strict access control of class members and methods:

1) Constructors must be private if objects are not allowed to be created directly from the outside via new.

2) Utility classes are not allowed to have public or default constructors.

3) Class non-static member variables shared with subclasses must be protected.

4) Class non-static member variables and used only in this class, must be private.

Class static member variables must be private if they are used only in this class.

6) Consider whether a static member variable is final.

Class member methods are called only from within the class and must be private.

8) Class member methods are only exposed to inherited classes, so limit them to protected.

Description: Any class, method, parameter, variable, strictly control access scope. Too wide access range is not conducive to module decoupling. If it is a private method, delete it if you want, but if it is a public service member method or a member variable, delete it. Variables like their own children, as far as possible in their line of sight, variable scope is too large, unlimited running around, then you will worry.