自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

這樣規(guī)范寫代碼,同事直呼“666”

開發(fā) 后端
本文介紹了十六項(xiàng)如何規(guī)范的寫出代碼,我們一起來看一下吧。

[[344095]]

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

當(dāng)遇到多個(gè)查詢條件,使用where 1=1 可以很方便的解決我們的問題,但是這樣很可能會(huì)造成非常大的性能損失,因?yàn)樘砑恿?“where 1=1 ”的過濾條件之后,數(shù)據(jù)庫(kù)系統(tǒng)就無法使用索引等查詢優(yōu)化策略,數(shù)據(jù)庫(kù)系統(tǒng)將會(huì)被迫對(duì)每行數(shù)據(jù)進(jìn)行掃描(即全表掃描) 以比較此行是否滿足過濾條件,當(dāng)表中的數(shù)據(jù)量較大時(shí)查詢速度會(huì)非常慢;此外,還會(huì)存在SQL 注入的風(fēng)險(xiǎn)。

反例: 

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

正例: 

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

UPDATE 操作也一樣,可以用標(biāo)記代替 1=1。

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

當(dāng)循環(huán)中只需要獲取Map 的主鍵key時(shí),迭代keySet() 是正確的;但是,當(dāng)需要主鍵key 和取值value 時(shí),迭代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);  

正例: 

  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();  

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

使用Collection.size() 來檢測(cè)是否為空在邏輯上沒有問題,但是使用Collection.isEmpty() 使得代碼更易讀,并且可以獲得更好的性能;除此之外,任何Collection.isEmpty() 實(shí)現(xiàn)的時(shí)間復(fù)雜度都是O(1) ,不需要多次循環(huán)遍歷,但是某些通過Collection.size() 方法實(shí)現(xiàn)的時(shí)間復(fù)雜度可能是O(n)

反例: 

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

正例: 

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

四、初始化集合時(shí)盡量指定其大小

盡量在初始化時(shí)指定集合的大小,能有效減少集合的擴(kuò)容次數(shù),因?yàn)榧厦看螖U(kuò)容的時(shí)間復(fù)雜度很可能時(shí)O(n),耗費(fèi)時(shí)間和性能。

反例: 

  1. //初始化list,往list 中添加元素反例: 
  2.  
  3. int[] arr = new int[]{1,2,3,4};  
  4. List<Integer> list = new ArrayList<>();  
  5. for (int i : arr){  
  6.  list.add(i);  

正例: 

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

五、使用StringBuilder 拼接字符串

一般的字符串拼接在編譯期Java 會(huì)對(duì)其進(jìn)行優(yōu)化,但是在循環(huán)中字符串的拼接Java 編譯期無法執(zhí)行優(yōu)化,所以需要使用StringBuilder 進(jìn)行替換。

反例: 

  1. //在循環(huán)中拼接字符串反例  
  2. String str = "" 
  3. for (int i = 0; i < 10; i++){  
  4.     //在循環(huán)中字符串拼接Java 不會(huì)對(duì)其進(jìn)行優(yōu)化  
  5.     str += i;  

正例: 

  1. //在循環(huán)中拼接字符串正例  
  2. String str1 = "Love" 
  3. String str2 = "Courage" 
  4. String strConcat = str1 + str2;  //Java 編譯器會(huì)對(duì)該普通模式的字符串拼接進(jìn)行優(yōu)化  
  5. StringBuilder sb = new StringBuilder();  
  6. for (int i = 0; i < 10; i++){  
  7.    //在循環(huán)中,Java 編譯器無法進(jìn)行優(yōu)化,所以要手動(dòng)使用StringBuilder  
  8.    &nbsp;sb.append(i);  

六、若需頻繁調(diào)用Collection.contains 方法則使用Set

在Java 集合類庫(kù)中,List的contains 方法普遍時(shí)間復(fù)雜度為O(n),若代碼中需要頻繁調(diào)用contains 方法查找數(shù)據(jù)則先將集合list 轉(zhuǎn)換成HashSet 實(shí)現(xiàn),將O(n) 的時(shí)間復(fù)雜度將為O(1)。

反例: 

  1. //頻繁調(diào)用Collection.contains() 反例  
  2. List<Object> list = new ArrayList<>();  
  3. for (int i = 0; i <= Integer.MAX_VALUE; i++){  
  4.     //時(shí)間復(fù)雜度為O(n)  
  5.     if (list.contains(i))  
  6.     System.out.println("list contains "+ i);  

正例: 

  1. //頻繁調(diào)用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.     //時(shí)間復(fù)雜度為O(1)  
  6.     if (set.contains(i)){  
  7.         System.out.println("list contains "+ i);  
  8.     }  

七、使用靜態(tài)代碼塊實(shí)現(xiàn)賦值靜態(tài)成員變量

對(duì)于集合類型的靜態(tài)成員變量,應(yīng)該使用靜態(tài)代碼塊賦值,而不是使用集合實(shí)現(xiàn)來賦值。

反例: 

  1. //賦值靜態(tài)成員變量反例 
  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. //賦值靜態(tài)成員變量正例  
  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. private static List<String> list = new ArrayList<>(); 
  9.  static {  
  10.     list.add("Sagittarius");  
  11.     list.add("Charming");  
  12.     list.add("Perfectionist");  

八、刪除未使用的局部變量、方法參數(shù)、私有方法、字段和多余的括號(hào)。

九、工具類中屏蔽構(gòu)造函數(shù)

工具類是一堆靜態(tài)字段和函數(shù)的集合,其不應(yīng)該被實(shí)例化;但是,Java 為每個(gè)沒有明確定義構(gòu)造函數(shù)的類添加了一個(gè)隱式公有構(gòu)造函數(shù),為了避免不必要的實(shí)例化,應(yīng)該顯式定義私有構(gòu)造函數(shù)來屏蔽這個(gè)隱式公有構(gòu)造函數(shù)。

反例: 

  1. public class PasswordUtils {  
  2. //工具類構(gòu)造函數(shù)反例  
  3. private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);  
  4. public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES"
  5. public static String encryptPassword(String aPassword) throws IOException {  
  6.     return new PasswordUtils(aPassword).encrypt();  

正例: 

  1. public class PasswordUtils {  
  2. //工具類構(gòu)造函數(shù)正例  
  3. private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);  
  4. //定義私有構(gòu)造函數(shù)來屏蔽這個(gè)隱式公有構(gòu)造函數(shù)  
  5. private PasswordUtils(){} 
  6. public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES" 
  7. public static String encryptPassword(String aPassword) throws IOException {  
  8.     return new PasswordUtils(aPassword).encrypt();  

十、刪除多余的異常捕獲并跑出

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

反例: 

  1. //多余異常反例  
  2. private static String fileReader(String fileName)throws IOException{  
  3.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {  
  4.         String line;  
  5.         StringBuilder builder = new StringBuilder();  
  6.         while ((line = reader.readLine()) != null) {  
  7.             builder.append(line);  
  8.         }  
  9.         return builder.toString();  
  10.     } catch (Exception e) {  
  11.         //僅僅是重復(fù)拋異常 未作任何處理  
  12.         throw e;  
  13.     }  

正例: 

  1. //多余異常正例  
  2. private static String fileReader(String fileName)throws IOException{  
  3.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {  
  4.         String line;  
  5.         StringBuilder builder = new StringBuilder();  
  6.         while ((line = reader.readLine()) != null) {  
  7.             builder.append(line);  
  8.         }  
  9.         return builder.toString();  
  10.         //刪除多余的拋異常,或增加其他處理:  
  11.         /*catch (Exception e) {  
  12.             return "fileReader exception";  
  13.         }*/  
  14.     }  

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

把其它對(duì)象或類型轉(zhuǎn)化為字符串時(shí),使用String.valueOf(value) 比 ""+value 的效率更高。

反例: 

  1. //把其它對(duì)象或類型轉(zhuǎn)化為字符串反例:  
  2. int num = 520 
  3. // "" + value  
  4. String strLove = "" + num; 

正例: 

  1. //把其它對(duì)象或類型轉(zhuǎn)化為字符串正例:  
  2. int num = 520 
  3. // String.valueOf() 效率更高  
  4. String strLove = String.valueOf(num); 

十二、避免使用BigDecimal(double)

BigDecimal(double) 存在精度損失風(fēng)險(xiǎn),在精確計(jì)算或值比較的場(chǎng)景中可能會(huì)導(dǎo)致業(yè)務(wù)邏輯異常。

反例: 

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

正例: 

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

十三、返回空數(shù)組和集合而非 null

若程序運(yùn)行返回null,需要調(diào)用方強(qiáng)制檢測(cè)null,否則就會(huì)拋出空指針異常;返回空數(shù)組或空集合,有效地避免了調(diào)用方因?yàn)槲礄z測(cè)null 而拋出空指針異常的情況,還可以刪除調(diào)用方檢測(cè)null 的語句使代碼更簡(jiǎn)潔。

反例: 

  1. //返回null 反例  
  2. public static Result[] getResults() {  
  3.     return null; 
  4.   
  5. public static List<Result> getResultList() {  
  6.     return null;  
  7.  
  8. public static Map<String, Result> getResultMap() {  
  9.     return null;  

正例: 

  1. //返回空數(shù)組和空集正例  
  2. public static Result[] getResults() {  
  3.     return new Result[0];  
  4.  
  5. public static List<Result> getResultList() {  
  6.     return Collections.emptyList();  
  7.  
  8. public static Map<String, Result> getResultMap() {  
  9.     return Collections.emptyMap();  

十四、優(yōu)先使用常量或確定值調(diào)用equals 方法

對(duì)象的equals 方法容易拋空指針異常,應(yīng)使用常量或確定有值的對(duì)象來調(diào)用equals 方法。

反例: 

  1. //調(diào)用 equals 方法反例  
  2. private static boolean fileReader(String fileName)throws IOException{  
  3.  // 可能拋空指針異常 
  4.   return fileName.equals("Charming");  

正例: 

  1. //調(diào)用 equals 方法正例  
  2. private static boolean fileReader(String fileName)throws IOException{  
  3.     // 使用常量或確定有值的對(duì)象來調(diào)用 equals 方法  
  4.     return "Charming".equals(fileName);   
  5.     //或使用:java.util.Objects.equals() 方法  
  6.    return Objects.equals("Charming",fileName);  

十五、枚舉的屬性字段必須是私有且不可變

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

反例: 

  1. public enum SwitchStatus {  
  2.     // 枚舉的屬性字段反例  
  3.     DISABLED(0, "禁用"),  
  4.     ENABLED(1, "啟用");  
  5.     public int value;  
  6.     private String description;  
  7.     private SwitchStatus(int value, String description) {  
  8.         this.value = value;  
  9.         this.description = description;  
  10.     }  
  11.     public String getDescription() {  
  12.         return description;  
  13.     }  
  14.     public void setDescription(String description) {  
  15.         this.description = description;  
  16.     }  

正例: 

  1. public enum SwitchStatus {  
  2.     // 枚舉的屬性字段正例  
  3.     DISABLED(0, "禁用"),  
  4.     ENABLED(1, "啟用");  
  5.     // final 修飾  
  6.     private final int value;  
  7.     private final String description;  
  8.     private SwitchStatus(int value, String description) {  
  9.         this.value = value;  
  10.         this.description = description;  
  11.     }  
  12.     // 沒有Setter 方法  
  13.     public int getValue() {  
  14.         return value;  
  15.     }  
  16.     public String getDescription() {  
  17.         return description;  
  18.     }  

十六、tring.split(String regex)部分關(guān)鍵字需要轉(zhuǎn)譯

使用字符串String 的plit 方法時(shí),傳入的分隔字符串是正則表達(dá)式,則部分關(guān)鍵字(比如 .[]()| 等)需要轉(zhuǎn)義。

反例: 

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

正例: 

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

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2021-07-20 06:37:33

CTO代碼程序員

2020-09-24 11:10:05

Python代碼字符串

2020-02-20 10:45:57

代碼JS開發(fā)

2022-05-07 07:33:55

TypeScript條件類型

2022-04-29 06:54:48

TS 映射類型User 類型

2022-06-08 08:01:28

模板字面量類型

2022-03-23 08:01:04

Python語言代碼

2022-12-20 08:32:02

2020-03-20 08:00:32

代碼程序員追求

2021-04-27 07:52:19

StarterSpring Boot配置

2017-06-26 09:40:50

Python代碼寫法

2017-07-07 16:57:35

代碼Python

2021-10-26 08:40:33

String Java面試題

2021-03-02 20:01:08

寫代碼開發(fā)工具idea

2022-04-11 08:20:36

編程輔助工具GitHubCopilot

2021-07-06 07:21:17

橋接模式組合

2024-12-26 16:47:48

2021-03-28 16:55:11

Python工具鏈代碼

2022-03-04 06:46:30

Python代碼

2015-07-02 11:20:17

程序員代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)