How to write Java code more normalized

How to write Java code more normalized

 

Many of the happiest people are those who own the least. But are we really so happy with our IPhones, our big houses, our fancy cars?

Forget Chuan Rusi, people who have everything are more afraid of losing.

 

Background: There is no need to say how to write Java code more regularly, the most important of which is to improve code performance, keep code away from bugs, and make code more elegant.

1. MyBatis should not write 1 = 1 for multiple query conditions

When multiple query conditions are encountered, using where 1=1 can be a convenient solution to our problem, but it is likely to cause a very large performance loss because after adding a filter condition of where 1=1, the database system will not be able to use query optimization strategies such as indexes, and the database system will be forcedEach row of data is scanned (i.e., full table scan) to compare whether the row meets the filtering criteria, and queries can be very slow when there is a large amount of data in the table; there is also a risk of SQL injection.

Counterexamples:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_rule_BookInfo t where 1=1
<if test="title !=null and title !='' ">
 AND title = #{title} 
</if> 
<if test="author !=null and author !='' ">
 AND author = #{author}
</if> 
</select>

Example:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_rule_BookInfo t
<where>
<if test="title !=null and title !='' ">
 title = #{title} 
</if>
<if test="author !=null and author !='' "> 
 AND author = #{author}
</if>
</where> 
</select>

The same is true for UPDATE operations, where the <set>tag can be used instead of 1=1.

2. Iterate entrySet() to get the key and value of a Map

Iterating keySet() is correct when only the primary key of the Map is needed in a loop; however, iterating entrySet() is more efficient when both the primary key and the value value are required, and it performs better than iterating keySet() first and then getting the value through get.

Counterexamples:

1 //Map Obtain value Counterexamples:
2         HashMap<String, String> map = new HashMap<>();
3         for (String key : map.keySet()){
4             String value = map.get(key);
5         }

Example:

1  //Map Obtain key & value Positive examples:
2         HashMap<String, String> map = new HashMap<>();
3         for (Map.Entry<String,String> entry : map.entrySet()){
4             String key = entry.getKey();
5             String value = entry.getValue();
6         }

3. Use Collection.isEmpty() to detect nulls

There is no logical problem using Collection.size() to detect nullability, but using Collection.isEmpty() makes the code easier to read and provides better performance; in addition, any Collection.isEmpty() implementation has O(1) time complexity and does not require multiple iterations, but some doThe time complexity achieved by the Collection.size() method may be O(n). O(1) Latitude Decrease Cycle Number Example

Counterexamples:

1 LinkedList<Object> collection = new LinkedList<>();
2         if (collection.size() == 0){
3             System.out.println("collection is empty.");
4         }

Example:

 1  LinkedList<Object> collection = new LinkedList<>();
 2         if (collection.isEmpty()){
 3             System.out.println("collection is empty.");
 4         }
 5         
 6         //Detect if it is null have access to CollectionUtils.isEmpty()
 7         if (CollectionUtils.isEmpty(collection)){
 8             System.out.println("collection is null.");
 9 
10         }

4. Specify the size of the collection whenever possible when initializing it

Specifying the size of the collection at initialization can effectively reduce the number of times the collection is expanded, since the time complexity of each expansion of the collection is likely to be O(n), time consuming and performance consuming.

Counterexamples:

1 //Initialization list,to list Add element counterexamples in:
2         int[] arr = new int[]{1,2,3,4};
3         List<Integer> list = new ArrayList<>();
4         for (int i : arr){
5             list.add(i);
6         }

Example:

1  //Initialization list,to list Add element examples in:
2         int[] arr = new int[]{1,2,3,4};
3         //Specify Set list Size of capacity
4         List<Integer> list = new ArrayList<>(arr.length);
5         for (int i : arr){
6             list.add(i);
7         }

5. Stitching Strings Using StringBuilder

Common string splicing is optimized in compile-time Java, but string splicing in loops cannot be optimized during compile-time Java, so StringBuilder is needed to replace it.

Counterexamples:

1  //Reverse stitching string in loop
2        String str = "";
3        for (int i = 0; i < 10; i++){
4            //String splicing in a loop Java It will not be optimized
5            str += i;
6        }

Example:

1   //Splicing string examples in loops
2        String str1 = "Love";
3        String str2 = "Courage";
4        String strConcat = str1 + str2;  //Java The compiler optimizes string splicing for this common pattern
5         StringBuilder sb = new StringBuilder();
6         for (int i = 0; i < 10; i++){
7            //In a loop, Java Compiler cannot optimize, so use it manually StringBuilder
8             sb.append(i);
9         }

6. Use Set if Collection.contains method needs to be called frequently

In Java collection class libraries, the contains method of List has a general time complexity of O(n). If the contains method needs to be called frequently in code to find data, first convert the collection list into a HashSet implementation, and then O(n) will have an O(1) time complexity.

Counterexamples:

1 //Frequent calls Collection.contains() Counterexamples
2         List<Object> list = new ArrayList<>();
3         for (int i = 0; i <= Integer.MAX_VALUE; i++){
4             //Time complexity is O(n)
5             if (list.contains(i))
6             System.out.println("list contains "+ i);
7         }

Example:

1 //Frequent calls Collection.contains() Positive examples
2         List<Object> list = new ArrayList<>();
3         Set<Object> set = new HashSet<>();
4         for (int i = 0; i <= Integer.MAX_VALUE; i++){
5             //Time complexity is O(1)
6             if (set.contains(i)){
7                 System.out.println("list contains "+ i);
8             }
9         }

7. Use static code blocks to assign static member variables

For static member variables of a collection type, static code block assignment should be used instead of a collection implementation.

Counterexamples:

 1 //Inverse Assignment Static Member Variable
 2     private static Map<String, Integer> map = new HashMap<String, Integer>(){
 3         {
 4             map.put("Leo",1);
 5             map.put("Family-loving",2);
 6             map.put("Cold on the out side passionate on the inside",3);
 7         }
 8     };
 9     private static List<String> list = new ArrayList<>(){
10         {
11             list.add("Sagittarius");
12             list.add("Charming");
13             list.add("Perfectionist");
14         }
15     };

Example:

 1  //Assigning positive static member variables
 2     private static Map<String, Integer> map = new HashMap<String, Integer>();
 3         static {
 4             map.put("Leo",1);
 5             map.put("Family-loving",2);
 6             map.put("Cold on the out side passionate on the inside",3);
 7         }
 8         
 9     private static List<String> list = new ArrayList<>();
10         static {
11             list.add("Sagittarius");
12             list.add("Charming");
13             list.add("Perfectionist");
14         }

8. Remove unused local variables, method parameters, private methods, fields, and unnecessary brackets.

9. Shielding constructors in tool classes

Tool classes are a collection of static fields and functions that should not be instantiated; however, Java adds an implicit public constructor to each class that does not explicitly define a constructor, and to avoid unnecessary instantiation, private constructors should be explicitly defined to block this implicit public constructorNumber.

Counterexamples:

1 public class PasswordUtils {
2     //Inverse Tool Class Constructor
3     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
4 
5     public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
6 
7     public static String encryptPassword(String aPassword) throws IOException {
8         return new PasswordUtils(aPassword).encrypt();
9     }

Example:

 1 public class PasswordUtils {
 2     //Positive example of tool class constructor
 3     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
 4 
 5     //Define a private constructor to block this implicit public constructor
 6     private PasswordUtils(){}
 7     
 8     public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
 9 
10     public static String encryptPassword(String aPassword) throws IOException {
11         return new PasswordUtils(aPassword).encrypt();
12     }

10. Delete redundant exception traps and run out

After catching an exception with the catch statement, if nothing is handled, the exception is simply thrown again, which is the same as not catching an exception. You can delete this code or add other handling.

Counterexamples:

 1 //Counterexamples of redundant exceptions
 2     private static String fileReader(String fileName)throws IOException{
 3 
 4         try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
 5             String line;
 6             StringBuilder builder = new StringBuilder();
 7             while ((line = reader.readLine()) != null) {
 8                 builder.append(line);
 9             }
10             return builder.toString();
11         } catch (Exception e) {
12             //Simply throw the exception repeatedly and do nothing
13             throw e;
14         }
15     }

Example:

 1 //Positive redundant anomalies
 2     private static String fileReader(String fileName)throws IOException{
 3 
 4         try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
 5             String line;
 6             StringBuilder builder = new StringBuilder();
 7             while ((line = reader.readLine()) != null) {
 8                 builder.append(line);
 9             }
10             return builder.toString();
11             //Remove unnecessary throws or add additional handling:
12             /*catch (Exception e) {
13                 return "fileReader exception";
14             }*/
15         }
16     }

11. String.valueOf(value) is used for string conversion instead of "" + value

String.valueOf(value) is more efficient than "" +value"when converting other objects or types to strings.

Counterexamples:

1 //Convert other objects or types to string counterexamples:
2             int num = 520;
3             // "" + value
4             String strLove = "" + num;

Example:

1 //Convert other objects or types into positive string examples:
2             int num = 520;
3             // String.valueOf() More efficient
4             String strLove = String.valueOf(num);

12. Avoid using BigDecimal(double)

BigDecimal(double) is at risk of loss of precision and may cause business logic abnormalities in scenarios where precise calculations or value comparisons occur.

Counterexamples:

1 // BigDecimal Counterexamples    
2         BigDecimal bigDecimal = new BigDecimal(0.11D);

Example:

1 // BigDecimal Positive examples
2         BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

Figure 1. BigDecimal precision loss

13. Return empty arrays and collections instead of null s

If the program runs to return null, the caller needs to force null detection, otherwise null pointer exceptions will be thrown; returning an empty array or collection effectively avoids the caller throwing null pointer exceptions because null is not detected; and deleting the caller's statement to detect null will make the code more concise.

Counterexamples:

 1  //Return null Counterexamples
 2     public static Result[] getResults() {
 3         return null;
 4     }
 5 
 6     public static List<Result> getResultList() {
 7         return null;
 8     }
 9 
10     public static Map<String, Result> getResultMap() {
11         return null;
12     }

Example:

 1  //Returns an empty array and a positive empty set
 2     public static Result[] getResults() {
 3         return new Result[0];
 4     }
 5 
 6     public static List<Result> getResultList() {
 7         return Collections.emptyList();
 8     }
 9 
10     public static Map<String, Result> getResultMap() {
11         return Collections.emptyMap();
12     }

14. Call equals method first with constant or deterministic value

The equals method of an object tends to throw null pointer exceptions, so the equals method should be called using a constant or an object with a certain value.

Counterexamples:

1 //call equals Method Counterexample
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // Possible null pointer exception thrown
5         return fileName.equals("Charming");
6  }

Example:

1 //call equals Positive Method Example
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // Called using a constant or an object with a value equals Method
5         return "Charming".equals(fileName);
6         
7         //Or use: java.util.Objects.equals() Method
8        return Objects.equals("Charming",fileName);
9  }

15. Enumerated attribute fields must be private and immutable

Enumerations are often used as constants, and the properties of these enumeration constants can be easily modified if there are public property fields or set field methods in the enumeration; ideally, the property fields in the enumeration are private and assigned to private constructors, without a corresponding Setter method, it is best to addUpper final modifier.

Counterexamples:

 1 public enum SwitchStatus {
 2     // Counterexamples of Enumerated Attribute Fields
 3     DISABLED(0, "Disable"),
 4     ENABLED(1, "Enable");
 5 
 6     public int value;
 7     private String description;
 8 
 9     private SwitchStatus(int value, String description) {
10         this.value = value;
11         this.description = description;
12     }
13 
14     public String getDescription() {
15         return description;
16     }
17 
18     public void setDescription(String description) {
19         this.description = description;
20     }
21 }

Example:

 1 public enum SwitchStatus {
 2     // Example of an enumerated attribute field
 3     DISABLED(0, "Disable"),
 4     ENABLED(1, "Enable");
 5 
 6     // final Modification
 7     private final int value;
 8     private final String description;
 9 
10     private SwitchStatus(int value, String description) {
11         this.value = value;
12         this.description = description;
13     }
14 
15     // No, Setter Method
16     public int getValue() {
17         return value;
18     }
19 
20     public String getDescription() {
21         return description;
22     }
23 }

16. Some keywords of tring.split(String regex) need to be translated

When using the plit method of string String, the incoming delimiter string is a regular expression, and some keywords (such as. []()\|, etc.) need to be escaped.

Counterexamples:

1 // String.split(String regex) Counterexamples
2         String[] split = "a.ab.abc".split(".");
3         System.out.println(Arrays.toString(split));   // The result is[]
4 
5         String[] split1 = "a|ab|abc".split("|");
6         System.out.println(Arrays.toString(split1));  // The result is["a", "|", "a", "b", "|", "a", "b", "c"]

Example:

1  // String.split(String regex) Positive examples
2         // . Translations required
3         String[] split2 = "a.ab.abc".split("\\.");
4         System.out.println(Arrays.toString(split2));  // The result is["a", "ab", "abc"]
5 
6         // | Translations required
7         String[] split3 = "a|ab|abc".split("\\|");
8         System.out.println(Arrays.toString(split3));  // The result is["a", "ab", "abc"]

Figure 2. Positive and negative examples of String.split (String regex)

 

 

People who have everything fear losing

Keywords: Java Attribute Database Mybatis

Added by 2paulm on Thu, 26 Sep 2019 19:42:34 +0300