1. 程式人生 > >如何更規範化編寫Java 程式碼

如何更規範化編寫Java 程式碼

如何更規範化編寫Java 程式碼

 

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?

忘川如斯,擁有一切的人才更怕失去。

 

背景:如何更規範化編寫Java 程式碼的重要性想必毋需多言,其中最重要的幾點當屬提高程式碼效能、使程式碼遠離Bug、令程式碼更優雅。

一、MyBatis 不要為了多個查詢條件而寫 1 = 1

      當遇到多個查詢條件,使用where 1=1 可以很方便的解決我們的問題,但是這樣很可能會造成非常大的效能損失,因為添加了 “where 1=1 ”的過濾條件之後,資料庫系統就無法使用索引等查詢優化策略,資料庫系統將會被迫對每行資料進行掃描(即全表掃描) 以比較此行是否滿足過濾條件,當表中的資料量較大時查詢速度會非常慢;此外,還會存在SQL 注入的風險。

反例:

<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>

正例:

<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>

UPDATE 操作也一樣,可以用<set> 標記代替 1=1。

二、 迭代entrySet() 獲取Map 的key 和value

      當迴圈中只需要獲取Map 的主鍵key時,迭代keySet() 是正確的;但是,當需要主鍵key 和取值value 時,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 後再去通過get 取值效能更佳。

反例:

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

正例:

1  //Map 獲取key & value 正例:
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         }

三、使用Collection.isEmpty() 檢測空

      使用Collection.size() 來檢測是否為空在邏輯上沒有問題,但是使用Collection.isEmpty() 使得程式碼更易讀,並且可以獲得更好的效能;除此之外,任何Collection.isEmpty() 實現的時間複雜度都是O(1) ,不需要多次迴圈遍歷,但是某些通過Collection.size() 方法實現的時間複雜度可能是O(n)。O(1)緯度減少迴圈次數 例子

反例:

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

正例:

 1  LinkedList<Object> collection = new LinkedList<>();
 2         if (collection.isEmpty()){
 3             System.out.println("collection is empty.");
 4         }
 5         
 6         //檢測是否為null 可以使用CollectionUtils.isEmpty()
 7         if (CollectionUtils.isEmpty(collection)){
 8             System.out.println("collection is null.");
 9 
10         }

四、初始化集合時儘量指定其大小

      儘量在初始化時指定集合的大小,能有效減少集合的擴容次數,因為集合每次擴容的時間複雜度很可能時O(n),耗費時間和效能。

反例:

1 //初始化list,往list 中新增元素反例:
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         }

正例:

1  //初始化list,往list 中新增元素正例:
2         int[] arr = new int[]{1,2,3,4};
3         //指定集合list 的容量大小
4         List<Integer> list = new ArrayList<>(arr.length);
5         for (int i : arr){
6             list.add(i);
7         }

五、使用StringBuilder 拼接字串

      一般的字串拼接在編譯期Java 會對其進行優化,但是在迴圈中字串的拼接Java 編譯期無法執行優化,所以需要使用StringBuilder 進行替換。

反例:

1  //在迴圈中拼接字串反例
2        String str = "";
3        for (int i = 0; i < 10; i++){
4            //在迴圈中字串拼接Java 不會對其進行優化
5            str += i;
6        }

正例:

1   //在迴圈中拼接字串正例
2        String str1 = "Love";
3        String str2 = "Courage";
4        String strConcat = str1 + str2;  //Java 編譯器會對該普通模式的字串拼接進行優化
5         StringBuilder sb = new StringBuilder();
6         for (int i = 0; i < 10; i++){
7            //在迴圈中,Java 編譯器無法進行優化,所以要手動使用StringBuilder
8             sb.append(i);
9         }

 六、若需頻繁呼叫Collection.contains 方法則使用Set

      在Java 集合類庫中,List的contains 方法普遍時間複雜度為O(n),若程式碼中需要頻繁呼叫contains 方法查詢資料則先將集合list 轉換成HashSet 實現,將O(n) 的時間複雜度將為O(1)。

反例:

1 //頻繁呼叫Collection.contains() 反例
2         List<Object> list = new ArrayList<>();
3         for (int i = 0; i <= Integer.MAX_VALUE; i++){
4             //時間複雜度為O(n)
5             if (list.contains(i))
6             System.out.println("list contains "+ i);
7         }

正例:

1 //頻繁呼叫Collection.contains() 正例
2         List<Object> list = new ArrayList<>();
3         Set<Object> set = new HashSet<>();
4         for (int i = 0; i <= Integer.MAX_VALUE; i++){
5             //時間複雜度為O(1)
6             if (set.contains(i)){
7                 System.out.println("list contains "+ i);
8             }
9         }

七、使用靜態程式碼塊實現賦值靜態成員變數

      對於集合型別的靜態成員變數,應該使用靜態程式碼塊賦值,而不是使用集合實現來賦值。

反例:

 1 //賦值靜態成員變數反例
 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     };

正例:

 1  //賦值靜態成員變數正例
 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         }

八、刪除未使用的區域性變數、方法引數、私有方法、欄位和多餘的括號

九、工具類中遮蔽建構函式

      工具類是一堆靜態欄位和函式的集合,其不應該被例項化;但是,Java 為每個沒有明確定義建構函式的類添加了一個隱式公有建構函式,為了避免不必要的例項化,應該顯式定義私有建構函式來遮蔽這個隱式公有建構函式。

反例:

1 public class PasswordUtils {
2     //工具類建構函式反例
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     }

正例:

 1 public class PasswordUtils {
 2     //工具類建構函式正例
 3     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
 4 
 5     //定義私有建構函式來遮蔽這個隱式公有建構函式
 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     }

十、刪除多餘的異常捕獲並跑出

      用catch 語句捕獲異常後,若什麼也不進行處理,就只是讓異常重新丟擲,這跟不捕獲異常的效果一樣,可以刪除這塊程式碼或新增別的處理。

反例:

 1 //多餘異常反例
 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             //僅僅是重複拋異常 未作任何處理
13             throw e;
14         }
15     }

正例:

 1 //多餘異常正例
 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             //刪除多餘的拋異常,或增加其他處理:
12             /*catch (Exception e) {
13                 return "fileReader exception";
14             }*/
15         }
16     }

十一、字串轉化使用String.valueOf(value) 代替 " " + value

      把其它物件或型別轉化為字串時,使用String.valueOf(value) 比 ""+value 的效率更高。

反例:

1 //把其它物件或型別轉化為字串反例:
2             int num = 520;
3             // "" + value
4             String strLove = "" + num;

正例:

1 //把其它物件或型別轉化為字串正例:
2             int num = 520;
3             // String.valueOf() 效率更高
4             String strLove = String.valueOf(num);

十二、避免使用BigDecimal(double)

      BigDecimal(double) 存在精度損失風險,在精確計算或值比較的場景中可能會導致業務邏輯異常。

反例:

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

正例:

1 // BigDecimal 正例
2         BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

圖1. BigDecimal 精度丟失

十三、返回空陣列和集合而非 null

      若程式執行返回null,需要呼叫方強制檢測null,否則就會丟擲空指標異常;返回空陣列或空集合,有效地避免了呼叫方因為未檢測null 而丟擲空指標異常的情況,還可以刪除呼叫方檢測null 的語句使程式碼更簡潔。

反例:

 1  //返回null 反例
 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     }

正例:

 1  //返回空陣列和空集正例
 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     }

十四、優先使用常量或確定值呼叫equals 方法

      物件的equals 方法容易拋空指標異常,應使用常量或確定有值的物件來呼叫equals 方法。

反例:

1 //呼叫 equals 方法反例
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // 可能拋空指標異常
5         return fileName.equals("Charming");
6  }

正例:

1 //呼叫 equals 方法正例
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // 使用常量或確定有值的物件來呼叫 equals 方法
5         return "Charming".equals(fileName);
6         
7         //或使用: java.util.Objects.equals() 方法
8        return Objects.equals("Charming",fileName);
9  }

十五、列舉的屬性欄位必須是私有且不可變

      列舉通常被當做常量使用,如果列舉中存在公共屬性欄位或設定欄位方法,那麼這些列舉常量的屬性很容易被修改;理想情況下,列舉中的屬性欄位是私有的,並在私有建構函式中賦值,沒有對應的Setter 方法,最好加上final 修飾符。

反例:

 1 public enum SwitchStatus {
 2     // 列舉的屬性欄位反例
 3     DISABLED(0, "禁用"),
 4     ENABLED(1, "啟用");
 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 }

正例:

 1 public enum SwitchStatus {
 2     // 列舉的屬性欄位正例
 3     DISABLED(0, "禁用"),
 4     ENABLED(1, "啟用");
 5 
 6     // final 修飾
 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     // 沒有Setter 方法
16     public int getValue() {
17         return value;
18     }
19 
20     public String getDescription() {
21         return description;
22     }
23 }

十六、tring.split(String regex)部分關鍵字需要轉譯

      使用字串String 的plit 方法時,傳入的分隔字串是正則表示式,則部分關鍵字(比如 .[]()\| 等)需要轉義。

反例:

1 // String.split(String regex) 反例
2         String[] split = "a.ab.abc".split(".");
3         System.out.println(Arrays.toString(split));   // 結果為[]
4 
5         String[] split1 = "a|ab|abc".split("|");
6         System.out.println(Arrays.toString(split1));  // 結果為["a", "|", "a", "b", "|", "a", "b", "c"]

正例:

1  // String.split(String regex) 正例
2         // . 需要轉譯
3         String[] split2 = "a.ab.abc".split("\\.");
4         System.out.println(Arrays.toString(split2));  // 結果為["a", "ab", "abc"]
5 
6         // | 需要轉譯
7         String[] split3 = "a|ab|abc".split("\\|");
8         System.out.println(Arrays.toString(split3));  // 結果為["a", "ab", "abc"]

圖2. String.split(String regex) 正反例

 

 

擁有一切的人才更怕失去

 

&n