OOP


1. [Mandatory] Avoid accessing static variables or static methods of this class through object references of a class. This will unnecessarily increase the number of compiler parses into scripts. Just use the class name to access them directly.


#2. [Mandatory] All override methods must be annotated with @Override.

Counterexample: Problems with getObject() and get 0 bject(). One is the letter O and the other is the number 0. Add @Override

to accurately determine whether the override is successful. In addition, if the method signature is modified in an abstract class, its implementation class will immediately compile and report an error.


#3. [Mandatory] Java variable parameters can be used only if they have the same parameter type and the same business meaning. Avoid using Object.

Note: Variable parameters must be placed at the end of the parameter list. (Students are encouraged to avoid variable parameter programming as much as possible)

Positive example: public User getUsers(String type, Integer... ids)

4. [Mandatory] The signature of the interface exposed to the outside world, In principle, modification of method signatures is not allowed to avoid any impact on interface callers. The @Deprecated annotation must be added when the interface is out of date, and clearly


33is##[ to explain the new interface or new service adopted.


#5. [Mandatory] Outdated classes or methods cannot be used.

Description:

The method decode(String encodeStr) in java . net . URLDecoder is obsolete. You should use the two-parameter decode(String source, String encode) instead. Since the interface provider is clearly an obsolete interface,

is obliged to provide a new interface at the same time; as the caller, it is obligated to verify the new implementation of the obsolete method.

6. [Mandatory] The equals method of Object is prone to throwing a null pointer exception. You should use a constant or an object with a certain value to call

equals.


Positive example:

" test " .equals(object);

######Counterexample: ### object.equals( " test " );### ######Note: ###It is recommended to use java . util . Objects # equals (tool class introduced in JDK 7)###############7. [Mandatory] All Comparison of values ​​between wrapper class objects of the same type is performed using the equals method. ###

Note: For Integer var =? assignment between -128 and 127, the Integer object is generated in IntegerCache . cache, and existing objects will be reused. Integer in this range The value can be judged directly using ==, but all data outside this range 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 usage standards for basic data types and packaged data types are as follows:

1) All POJO class attributes must Use wrapper data types.

2) The return value and parameters of RPC methods must use wrapped data types.

3) All local variables [recommended] use basic data types.

Note: The POJO class attribute does not have an initial value to remind users that when they need to use it, they must explicitly assign the value themselves to avoid any

NPE issues or storage. Inspections are all ensured by the user.

Positive example: The query result of the database may be null because of automatic unboxing and receiving NPE risks with basic data types.

Counter example: For example, display the rise and fall of the total transaction volume, that is, plus or minus x %, x is the basic data type, and the RPC service is called. When the call is unsuccessful, the returned Default value, page display: 0%, which is unreasonable and should be displayed as a dash -. Therefore, the null value of the wrapped data type can represent additional information, such as: remote call failure and abnormal exit.


9. [Mandatory] When defining POJO classes such as DO / DTO / VO, do not set any attribute default values.

Counterexample: The default value of gmtCreate of the POJO class is new Date(); However, this attribute does not have a specific

value when updating other data. This field was updated when the field was added, causing the creation time to be modified to the current time.


10. [Mandatory] When adding new attributes to the serialization class, please do not modify the serialVersionUID field to avoid deserialization failure; if is completely incompatible with upgrades, avoid Deserialization is confusing, then please modify the serialVersionUID value.

Note: Note that inconsistent serialVersionUID will throw a serialization runtime exception.


11. [Mandatory] It is forbidden to add any business logic in the construction method. If there is initialization logic, please put it in the init method.


12. [Mandatory] The POJO class must write the toString method. When using the IDE tool: source > generate toString, if you inherit another POJO class, be sure to add super . toString in front.

Note: When an exception is thrown during method execution, you can directly call POJO's toString() method to print its attribute value, which is convenient for troubleshooting

.


13. [Recommendation] When using index to access the array obtained by String's split method, you need to check whether there is content after the last delimiter, otherwise There is a risk of throwing IndexOutOfBoundsException.

Instructions:

String str = "a,b,c,,";
String[] ary = str.split(",");
//预期大于 3,结果是 3
System.out.println(ary.length);


14. [Recommendation] When a class has multiple constructors, or multiple Methods with the same name, these methods should be placed together in order, for easy reading.


15. [Recommendation] The order of definition of methods within a class is: public method or protected method > private method > getter / setter method.

Explanation: Public methods are the methods that callers and maintainers of the class are most concerned about, and are best displayed on the first screen; although protected methods are only of concern to subclasses , they are also It may be the core method under the "template design mode"; and the outside of the private method generally does not need special care, it is a black box implementation; because the value of method information is low, all getter/setter methods of Service and DAO Place it at the end of the class body.


16. [Recommendation] In the setter method, the parameter name must be consistent with the class member variable name, this. member name = parameter name. In the

getter/setter method, try not to add business logic and increase the difficulty of troubleshooting.

Counter example:

public Integer getData(){
if(true) {
return data + 100;
} else {
return data - 100;
}
}


17. [Recommended] Use the append method of StringBuilder to connect strings in the loop body Extension.

Counter example:

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

Explanation:

The decompiled bytecode file shows that each loop will create a new StringBuilder object, and then proceed append operation, and finally returns the String object through the toString method, causing a waste of memory resources.


18. [Recommendation] final can improve the response efficiency of the program. When declared as final:

1) Variables that do not need to be reassigned , including class attributes and local variables.

2) Add final before the object parameter, indicating that the reference point is not allowed to be modified.

3) Class methods must not be overridden.


19. [Recommended] Use the clone method of Object with caution to copy objects.

Note:

The clone method of the object defaults to a shallow copy. If you want to implement a deep copy, you need to override the clone method to implement a copy of the attribute object .


20. [Recommendation] Strict access control to class members and methods:

1) If external objects are not allowed to be created directly through new, then the constructor must be private.

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

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

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

5) If a class static member variable is only used in this class, it must be private.

6) If it is a static member variable, you must consider whether it is final.

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

8) Class member methods are only public to inherited classes, so they are restricted to protected.

Note: The access scope of any class, method, parameter, or variable is strictly controlled. Too broad an access scope is not conducive to module decoupling. Thoughts: If it is a private method, delete it if you want, but if it is a public Service method, or a public member variable, delete it, and your palms will sweat a little? Variables are like your own children. Try to keep them within your own sight. The scope of variables is too large. If they run around without restrictions, you will worry.