成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

消滅 Java 代碼的“壞味道”

開發 后端
代碼中的"壞味道",如"私欲"如"灰塵",每天都在增加,一日不去清除,便會越累越多。如果用功去清除這些"壞味道",不僅能提高自己的編碼水平,也能使代碼變得"精白無一毫不徹"。

 [[278764]]

代碼中的"壞味道",如"私欲"如"灰塵",每天都在增加,一日不去清除,便會越累越多。如果用功去清除這些"壞味道",不僅能提高自己的編碼水平,也能使代碼變得"精白無一毫不徹"。這里,一直從事Java研發相關工作的阿里高級地圖技術工程師王超,整理了日常工作中的一些"壞味道",及清理方法,供大家參考。

讓代碼性能更高

需要 Map 的主鍵和取值時,應該迭代 entrySet()

當循環中只需要 Map 的主鍵時,迭代 keySet() 是正確的。但是,當需要主鍵和取值時,迭代 entrySet() 才是更高效的做法,比先迭代 keySet() 后再去 get 取值性能更佳。

反例:

  1. Map<String, String> map = ...; 
  2. for (String key : map.keySet()) { 
  3.     String value = map.get(key); 
  4.     ... 

正例:

  1. Map<String, String> map = ...; 
  2. for (Map.Entry<String, String> entry : map.entrySet()) { 
  3.     String key = entry.getKey(); 
  4.     String value = entry.getValue(); 
  5.     ... 

應該使用Collection.isEmpty()檢測空

使用 Collection.size() 來檢測空邏輯上沒有問題,但是使用 Collection.isEmpty()使得代碼更易讀,并且可以獲得更好的性能。任何 Collection.isEmpty() 實現的時間復雜度都是 O(1) ,但是某些 Collection.size() 實現的時間復雜度可能是 O(n) 。

反例:

  1. if (collection.size() == 0) { 
  2.     ... 

正例:

  1. if (collection.isEmpty()) { 
  2.     ... 

如果需要還需要檢測 null ,可采用CollectionUtils.isEmpty(collection)和CollectionUtils.isNotEmpty(collection)。

不要把集合對象傳給自己

此外,由于某些方法要求參數在執行期間保持不變,因此將集合傳遞給自身可能會導致異常行為。

反例:

  1. List<String> list = new ArrayList<>(); 
  2. list.add("Hello"); 
  3. list.add("World"); 
  4. if (list.containsAll(list)) { // 無意義,總是返回true 
  5.     ... 
  6. list.removeAll(list); // 性能差, 直接使用clear() 

集合初始化盡量指定大小

java 的集合類用起來十分方便,但是看源碼可知,集合也是有大小限制的。每次擴容的時間復雜度很有可能是 O(n) ,所以盡量指定可預知的集合大小,能減少集合的擴容次數。

反例:

  1. int[] arr = new int[]{1, 2, 3}; 
  2. List<Integer> list = new ArrayList<>(); 
  3. for (int i : arr) { 
  4.     list.add(i); 

正例:

  1. int[] arr = new int[]{1, 2, 3}; 
  2. List<Integer> list = new ArrayList<>(arr.length); 
  3. for (int i : arr) { 
  4.     list.add(i); 
  5.  
  6.  

字符串拼接使用 StringBuilder

一般的字符串拼接在編譯期 java 會進行優化,但是在循環中字符串拼接, java 編譯期無法做到優化,所以需要使用 StringBuilder 進行替換。

反例:

  1. String s = ""
  2. for (int i = 0; i < 10; i++) { 
  3.     s += i; 

正例:

  1. String a = "a"
  2. String b = "b"
  3. String c = "c"
  4. String s = a + b + c; // 沒問題,java編譯器會進行優化 
  5. StringBuilder sb = new StringBuilder(); 
  6. for (int i = 0; i < 10; i++) { 
  7.     sb.append(i);  // 循環中,java編譯器無法進行優化,所以要手動使用StringBuilder 

List 的隨機訪問

大家都知道數組和鏈表的區別:數組的隨機訪問效率更高。當調用方法獲取到 List 后,如果想隨機訪問其中的數據,并不知道該數組內部實現是鏈表還是數組,怎么辦呢?可以判斷它是否實現* RandomAccess *接口。

正例:

  1. // 調用別人的服務獲取到list 
  2. List<Integer> list = otherService.getList(); 
  3. if (list instanceof RandomAccess) { 
  4.     // 內部數組實現,可以隨機訪問 
  5.     System.out.println(list.get(list.size() - 1)); 
  6. else { 
  7.     // 內部可能是鏈表實現,隨機訪問效率低 

頻繁調用 Collection.contains 方法請使用 Set

在 java 集合類庫中,List 的 contains 方法普遍時間復雜度是 O(n) ,如果在代碼中需要頻繁調用 contains 方法查找數據,可以先將 list 轉換成 HashSet 實現,將 O(n) 的時間復雜度降為 O(1) 。

反例:

  1. ArrayList<Integer> list = otherService.getList(); 
  2. for (int i = 0; i <= Integer.MAX_VALUE; i++) { 
  3.     // 時間復雜度O(n) 
  4.     list.contains(i); 

正例:

  1. ArrayList<Integer> list = otherService.getList(); 
  2. Set<Integerset = new HashSet(list); 
  3. for (int i = 0; i <= Integer.MAX_VALUE; i++) { 
  4.     // 時間復雜度O(1) 
  5.     set.contains(i); 

讓代碼更優雅

長整型常量后添加大寫 L

在使用長整型常量值時,后面需要添加 L ,必須是大寫的 L ,不能是小寫的 l ,小寫 l 容易跟數字 1 混淆而造成誤解。

反例:

  1. long value = 1l; 
  2. long max = Math.max(1L, 5); 

正例:

  1. long value = 1L; 
  2. long max = Math.max(1L, 5L); 

不要使用魔法值

當你編寫一段代碼時,使用魔法值可能看起來很明確,但在調試時它們卻不顯得那么明確了。這就是為什么需要把魔法值定義為可讀取常量的原因。但是,-1、0 和 1不被視為魔法值。

反例:

  1. for (int i = 0; i < 100; i++){ 
  2.     ... 
  3. if (a == 100) { 
  4.     ... 

正例:

  1. private static final int MAX_COUNT = 100; 
  2. for (int i = 0; i < MAX_COUNT; i++){ 
  3.     ... 
  4. if (count == MAX_COUNT) { 
  5.     ... 

不要使用集合實現來賦值靜態成員變量

對于集合類型的靜態成員變量,不要使用集合實現來賦值,應該使用靜態代碼塊賦值。

反例:

  1. private static Map<String, Integer> map = new HashMap<String, Integer>() { 
  2.     { 
  3.         put("a", 1); 
  4.         put("b", 2); 
  5.     } 
  6. }; 
  7.  
  8.  
  9. private static List<String> list = new ArrayList<String>() { 
  10.     { 
  11.         add("a"); 
  12.         add("b"); 
  13.     } 
  14. }; 

正例:

  1. private static Map<String, Integer> map = new HashMap<>(); 
  2. static { 
  3.     map.put("a", 1); 
  4.     map.put("b", 2); 
  5. }; 
  6.  
  7.  
  8. private static List<String> list = new ArrayList<>(); 
  9. static { 
  10.     list.add("a"); 
  11.     list.add("b"); 
  12. }; 

建議使用 try-with-resources 語句

Java 7 中引入了 try-with-resources 語句,該語句能保證將相關資源關閉,優于原來的 try-catch-finally 語句,并且使程序代碼更安全更簡潔。

反例:

  1. private void handle(String fileName) { 
  2.     BufferedReader reader = null
  3.     try { 
  4.         String line; 
  5.         reader = new BufferedReader(new FileReader(fileName)); 
  6.         while ((line = reader.readLine()) != null) { 
  7.             ... 
  8.         } 
  9.     } catch (Exception e) { 
  10.         ... 
  11.     } finally { 
  12.         if (reader != null) { 
  13.             try { 
  14.                 reader.close(); 
  15.             } catch (IOException e) { 
  16.                 ... 
  17.             } 
  18.         } 
  19.     } 

正例:

  1. private void handle(String fileName) { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         while ((line = reader.readLine()) != null) { 
  5.             ... 
  6.         } 
  7.     } catch (Exception e) { 
  8.         ... 
  9.     } 

刪除未使用的私有方法和字段

刪除未使用的私有方法和字段,使代碼更簡潔更易維護。若有需要再使用,可以從歷史提交中找回。

反例:

  1. public class DoubleDemo1 { 
  2.     private int unusedField = 100; 
  3.     private void unusedMethod() { 
  4.         ... 
  5.     } 
  6.     public int sum(int a, int b) { 
  7.         return a + b; 
  8.     } 

正例:

  1. public class DoubleDemo1 { 
  2.     public int sum(int a, int b) { 
  3.         return a + b; 
  4.     } 

刪除未使用的局部變量

刪除未使用的局部變量,使代碼更簡潔更易維護。

反例:

  1. public int sum(int a, int b) { 
  2.     int c = 100; 
  3.     return a + b; 

正例:

  1. public int sum(int a, int b) { 
  2.     return a + b; 

刪除未使用的方法參數

未使用的方法參數具有誤導性,刪除未使用的方法參數,使代碼更簡潔更易維護。但是,由于重寫方法是基于父類或接口的方法定義,即便有未使用的方法參數,也是不能刪除的。

反例:

  1. public int sum(int a, int b, int c) { 
  2.     return a + b; 

正例:

  1. public int sum(int a, int b) { 
  2.     return a + b; 

刪除表達式的多余括號

對應表達式中的多余括號,有人認為有助于代碼閱讀,也有人認為完全沒有必要。對于一個熟悉 Java 語法的人來說,表達式中的多余括號反而會讓代碼顯得更繁瑣。

反例:

  1. return (x); 
  2. return (x + 2); 
  3. int x = (y * 3) + 1; 
  4. int m = (n * 4 + 2); 

正例:

  1. return x; 
  2. return x + 2; 
  3. int x = y * 3 + 1; 
  4. int m = n * 4 + 2; 

工具類應該屏蔽構造函數

工具類是一堆靜態字段和函數的集合,不應該被實例化。但是,Java 為每個沒有明確定義構造函數的類添加了一個隱式公有構造函數。所以,為了避免 java "小白"使用有誤,應該顯式定義私有構造函數來屏蔽這個隱式公有構造函數。

反例:

  1. public class MathUtils { 
  2.     public static final double PI = 3.1415926D; 
  3.     public static int sum(int a, int b) { 
  4.         return a + b; 
  5.     } 

正例:

  1. public class MathUtils { 
  2.     public static final double PI = 3.1415926D; 
  3.     private MathUtils() {} 
  4.     public static int sum(int a, int b) { 
  5.         return a + b; 
  6.     } 

刪除多余的異常捕獲并拋出

用 catch 語句捕獲異常后,什么也不進行處理,就讓異常重新拋出,這跟不捕獲異常的效果一樣,可以刪除這塊代碼或添加別的處理。

反例:

  1. private static String readFile(String fileName) throws IOException { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         StringBuilder builder = new StringBuilder(); 
  5.         while ((line = reader.readLine()) != null) { 
  6.             builder.append(line); 
  7.         } 
  8.         return builder.toString(); 
  9.     } catch (Exception e) { 
  10.         throw e; 
  11.     } 

正例:

  1. private static String readFile(String fileName) throws IOException { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         StringBuilder builder = new StringBuilder(); 
  5.         while ((line = reader.readLine()) != null) { 
  6.             builder.append(line); 
  7.         } 
  8.         return builder.toString(); 
  9.     } 

公有靜態常量應該通過類訪問

雖然通過類的實例訪問公有靜態常量是允許的,但是容易讓人它誤認為每個類的實例都有一個公有靜態常量。所以,公有靜態常量應該直接通過類訪問。

反例:

  1. public class User { 
  2.     public static final String CONST_NAME = "name"
  3.     ... 
  4.  
  5.  
  6. User user = new User(); 
  7. String nameKey = user.CONST_NAME; 

正例:

  1. public class User { 
  2.     public static final String CONST_NAME = "name"
  3.     ... 
  4.  
  5.  
  6. String nameKey = User.CONST_NAME; 

不要用NullPointerException判斷空

空指針異常應該用代碼規避(比如檢測不為空),而不是用捕獲異常的方式處理。

反例:

  1. public String getUserName(User user) { 
  2.     try { 
  3.         return user.getName(); 
  4.     } catch (NullPointerException e) { 
  5.         return null
  6.     } 

正例:

  1. public String getUserName(User user) { 
  2.     if (Objects.isNull(user)) { 
  3.         return null
  4.     } 
  5.     return user.getName(); 

使用String.valueOf(value)代替""+value

當要把其它對象或類型轉化為字符串時,使用 String.valueOf(value) 比""+value 的效率更高。

反例:

  1. int i = 1; 
  2. String s = "" + i; 

正例:

  1. int i = 1; 
  2. String s = String.valueOf(i); 

過時代碼添加 @Deprecated 注解

當一段代碼過時,但為了兼容又無法直接刪除,不希望以后有人再使用它時,可以添加 @Deprecated 注解進行標記。在文檔注釋中添加 @deprecated 來進行解釋,并提供可替代方案。

正例:

  1. /** 
  2.  * 保存 
  3.  * 
  4.  * @deprecated 此方法效率較低,請使用{@link newSave()}方法替換它 
  5.  */ 
  6. @Deprecated 
  7. public void save(){ 
  8.     // do something 

讓代碼遠離 bug

禁止使用構造方法 BigDecimal(double)

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

反例:

  1. BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115... 

正例:

  1. BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1 

返回空數組和空集合而不是 null

返回 null ,需要調用方強制檢測 null ,否則就會拋出空指針異常。返回空數組或空集合,有效地避免了調用方因為未檢測 null 而拋出空指針異常,還可以刪除調用方檢測 null 的語句使代碼更簡潔。

反例:

  1. public static Result[] getResults() { 
  2.     return null
  3.  
  4.  
  5. public static List<Result> getResultList() { 
  6.     return null
  7.  
  8.  
  9. public static Map<String, Result> getResultMap() { 
  10.     return null
  11.  
  12.  
  13. public static void main(String[] args) { 
  14.     Result[] results = getResults(); 
  15.     if (results != null) { 
  16.         for (Result result : results) { 
  17.             ... 
  18.         } 
  19.     } 
  20.  
  21.  
  22.     List<Result> resultList = getResultList(); 
  23.     if (resultList != null) { 
  24.         for (Result result : resultList) { 
  25.             ... 
  26.         } 
  27.     } 
  28.  
  29.  
  30.     Map<String, Result> resultMap = getResultMap(); 
  31.     if (resultMap != null) { 
  32.         for (Map.Entry<String, Result> resultEntry : resultMap) { 
  33.             ... 
  34.         } 
  35.     } 

正例:

  1. public static Result[] getResults() { 
  2.     return new Result[0]; 
  3.  
  4.  
  5. public static List<Result> getResultList() { 
  6.     return Collections.emptyList(); 
  7.  
  8.  
  9. public static Map<String, Result> getResultMap() { 
  10.     return Collections.emptyMap(); 
  11.  
  12.  
  13. public static void main(String[] args) { 
  14.     Result[] results = getResults(); 
  15.     for (Result result : results) { 
  16.         ... 
  17.     } 
  18.  
  19.  
  20.     List<Result> resultList = getResultList(); 
  21.     for (Result result : resultList) { 
  22.         ... 
  23.     } 
  24.  
  25.  
  26.     Map<String, Result> resultMap = getResultMap(); 
  27.     for (Map.Entry<String, Result> resultEntry : resultMap) { 
  28.         ... 
  29.     } 

優先使用常量或確定值來調用 equals 方法

對象的 equals 方法容易拋空指針異常,應使用常量或確定有值的對象來調用 equals 方法。當然,使用 java.util.Objects.equals() 方法是最佳實踐。

反例:

  1. public void isFinished(OrderStatus status) { 
  2.     return status.equals(OrderStatus.FINISHED); // 可能拋空指針異常 

正例:

  1. public void isFinished(OrderStatus status) { 
  2.     return OrderStatus.FINISHED.equals(status); 
  3.  
  4.  
  5. public void isFinished(OrderStatus status) { 
  6.     return Objects.equals(status, OrderStatus.FINISHED); 

枚舉的屬性字段必須是私有不可變

枚舉通常被當做常量使用,如果枚舉中存在公共屬性字段或設置字段方法,那么這些枚舉常量的屬性很容易被修改。理想情況下,枚舉中的屬性字段是私有的,并在私有構造函數中賦值,沒有對應的 Setter 方法,最好加上 final 修飾符。

反例:

  1. public enum UserStatus { 
  2.     DISABLED(0, "禁用"), 
  3.     ENABLED(1, "啟用"); 
  4.  
  5.  
  6.     public int value; 
  7.     private String description; 
  8.  
  9.  
  10.     private UserStatus(int value, String description) { 
  11.         this.value = value; 
  12.         this.description = description; 
  13.     } 
  14.  
  15.  
  16.     public String getDescription() { 
  17.         return description; 
  18.     } 
  19.  
  20.  
  21.     public void setDescription(String description) { 
  22.         this.description = description; 
  23.     } 

正例:

  1. public enum UserStatus { 
  2.     DISABLED(0, "禁用"), 
  3.     ENABLED(1, "啟用"); 
  4.  
  5.  
  6.     private final int value; 
  7.     private final String description; 
  8.  
  9.  
  10.     private UserStatus(int value, String description) { 
  11.         this.value = value; 
  12.         this.description = description; 
  13.     } 
  14.  
  15.  
  16.     public int getValue() { 
  17.         return value; 
  18.     } 
  19.  
  20.  
  21.     public String getDescription() { 
  22.         return description; 
  23.     } 

小心String.split(String regex)

字符串 String 的 split 方法,傳入的分隔字符串是正則表達式!部分關鍵字(比如.[]()\| 等)需要轉義。

反例:

  1. "a.ab.abc".split("."); // 結果為[] 
  2. "a|ab|abc".split("|"); // 結果為["a""|""a""b""|""a""b""c"

正例:

  1. "a.ab.abc".split("\\."); // 結果為["a""ab""abc"
  2. "a|ab|abc".split("\\|"); // 結果為["a""ab""abc"

總結

這篇文章,可以說是從事 Java 開發的經驗總結,分享出來以供大家參考。希望能幫大家避免踩坑,讓代碼更加高效優雅。

責任編輯:武曉燕 來源: 阿里技術
相關推薦

2020-06-12 08:21:58

JavaScript代碼開發

2015-07-29 13:22:40

.NET代碼

2012-07-13 09:38:15

項目代碼

2012-07-13 09:35:58

PHP

2021-05-26 11:50:37

代碼優化Java

2012-07-19 10:42:17

項目

2018-08-24 21:25:02

編程語言代碼重構GitHub

2022-01-26 10:29:24

微服務循環依賴代碼

2022-05-07 10:01:20

好代碼壞代碼

2020-12-01 08:36:10

代碼程序員函數

2020-04-26 10:01:14

編程學習技術

2024-08-05 14:10:04

2019-09-29 16:17:25

Java代碼性能編程語言

2024-06-19 10:04:15

ifC#代碼

2018-03-29 14:51:59

智能公廁AI

2023-08-04 08:52:52

Optional消滅空指針

2012-05-28 15:32:05

PHP

2024-09-05 10:17:34

2024-12-11 18:24:29

2020-02-14 16:40:22

Java無可匹敵變身裝備
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美日韩中文在线 | 欧美亚洲视频在线观看 | 日韩精品人成在线播放 | 午夜国产一级片 | 亚洲成人自拍 | 久久国产亚洲 | 色综合视频 | 国产午夜精品一区二区三区嫩草 | 久久99精品国产自在现线小黄鸭 | 精品国产欧美日韩不卡在线观看 | 一级做a爰片久久毛片 | 爱草在线 | 午夜黄色影院 | 国产精品一区二区欧美 | 黄色一级视频 | 日韩av一区二区在线观看 | 欧美成人一区二区三区 | 国产免费又黄又爽又刺激蜜月al | 欧美日韩在线免费观看 | 91视频a | 欧美多人在线 | 久久精品 | 成人精品久久日伦片大全免费 | 欧美一级免费看 | 色婷婷国产精品综合在线观看 | 欧美一区在线视频 | 色综合久久久久 | 久久亚洲国产精品日日av夜夜 | 精品三级在线观看 | 国产高清在线 | 中文字幕av一区二区三区 | 午夜在线观看视频 | 日韩av美女电影 | 一级黄色大片 | 亚洲欧美中文日韩在线v日本 | 一级片在线免费播放 | 日韩综合在线 | 久久亚洲一区 | 午夜国产精品视频 | 天堂一区 | 韩日精品视频 |