02.27 寫出一手漂亮的代碼,你需要遵守這些規範

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

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

反例:

<code><select> select count(*) from t_rule_BookInfo t where 1=1 AND title = #{title}   AND author = #{author} /<select>/<code>

正例:

<code><select> select count(*) from t_rule_BookInfo t<where> title = #{title}   AND author = #{author}/<where> /<select>/<code>

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

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

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

反例:

<code>//Map 獲取value 反例:HashMap<string> map = new HashMap<>();for (String key : map.keySet()){    String value = map.get(key);}/<string>/<code>

正例:

<code>//Map 獲取key & value 正例:HashMap<string> map = new HashMap<>();for (Map.Entry<string> entry : map.entrySet()){ String key = entry.getKey(); String value = entry.getValue();}/<string>/<string>/<code>

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

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

反例:

<code>LinkedList<object> collection = new LinkedList<>();if (collection.size() == 0){ System.out.println("collection is empty.");}/<object>/<code>

正例:

<code>LinkedList<object> collection = new LinkedList<>();if (collection.isEmpty()){    System.out.println("collection is empty.");}//檢測是否為null 可以使用CollectionUtils.isEmpty()if (CollectionUtils.isEmpty(collection)){    System.out.println("collection is null.");}/<object>/<code>

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

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

反例:

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

正例:

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

五、使用StringBuilder 拼接字符串

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

反例:

<code>//在循環中拼接字符串反例String str = "";for (int i = 0; i < 10; i++){    //在循環中字符串拼接Java 不會對其進行優化    str += i;}/<code>

正例:

<code>//在循環中拼接字符串正例String str1 = "Love";String str2 = "Courage";String strConcat = str1 + str2;  //Java 編譯器會對該普通模式的字符串拼接進行優化StringBuilder sb = new StringBuilder();for (int i = 0; i < 10; i++){   //在循環中,Java 編譯器無法進行優化,所以要手動使用StringBuilder    sb.append(i);}/<code>

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

在Java 集合類庫中,List的contains 方法普遍時間複雜度為O(n),若代碼中需要頻繁調用contains 方法查找數據則先將集合list 轉換成HashSet 實現,將O(n) 的時間複雜度將為O(1)。

反例:

<code>//頻繁調用Collection.contains() 反例List<object> list = new ArrayList<>();for (int i = 0; i <= Integer.MAX_VALUE; i++){    //時間複雜度為O(n)    if (list.contains(i))    System.out.println("list contains "+ i);}/<object>/<code>

正例:

<code>//頻繁調用Collection.contains() 正例List<object> list = new ArrayList<>();Set<object> set = new HashSet<>();for (int i = 0; i <= Integer.MAX_VALUE; i++){    //時間複雜度為O(1)    if (set.contains(i)){        System.out.println("list contains "+ i);    }}/<object>/<object>/<code>

七、使用靜態代碼塊實現賦值靜態成員變量

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

反例:

<code>//賦值靜態成員變量反例private static Map<string> map = new HashMap<string>(){    {        map.put("Leo",1);        map.put("Family-loving",2);        map.put("Cold on the out side passionate on the inside",3);    }};private static List<string> list = new ArrayList<>(){    {        list.add("Sagittarius");        list.add("Charming");        list.add("Perfectionist");    }};/<string>/<string>/<string>/<code>

正例:

<code>//賦值靜態成員變量正例private static Map<string> map = new HashMap<string>();static {    map.put("Leo",1);    map.put("Family-loving",2);    map.put("Cold on the out side passionate on the inside",3);}private static List<string> list = new ArrayList<>();static {    list.add("Sagittarius");    list.add("Charming");    list.add("Perfectionist");}/<string>/<string>/<string>/<code> 

八、刪除未使用的局部變量、方法參數、私有方法、字段和多餘的括號。

九、工具類中屏蔽構造函數

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

反例:

<code>public class PasswordUtils {//工具類構造函數反例private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";public static String encryptPassword(String aPassword) throws IOException {    return new PasswordUtils(aPassword).encrypt();}/<code>

正例:

<code>public class PasswordUtils {//工具類構造函數正例private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);//定義私有構造函數來屏蔽這個隱式公有構造函數private PasswordUtils(){}public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";public static String encryptPassword(String aPassword) throws IOException {    return new PasswordUtils(aPassword).encrypt();}/<code>

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

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

反例:

<code>//多餘異常反例private static String fileReader(String fileName)throws IOException{    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {        String line;        StringBuilder builder = new StringBuilder();        while ((line = reader.readLine()) != null) {            builder.append(line);        }        return builder.toString();    } catch (Exception e) {        //僅僅是重複拋異常 未作任何處理        throw e;    }}/<code> 

正例:

<code>//多餘異常正例private static String fileReader(String fileName)throws IOException{    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {        String line;        StringBuilder builder = new StringBuilder();        while ((line = reader.readLine()) != null) {            builder.append(line);        }        return builder.toString();        //刪除多餘的拋異常,或增加其他處理:        /*catch (Exception e) {            return "fileReader exception";        }*/    }}/<code>

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

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

反例:

<code>//把其它對象或類型轉化為字符串反例:int num = 520;// "" + valueString strLove = "" + num;/<code>

正例:

<code>//把其它對象或類型轉化為字符串正例:int num = 520;// String.valueOf() 效率更高String strLove = String.valueOf(num);/<code>

十二、避免使用BigDecimal(double)

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

反例:

<code>// BigDecimal 反例    BigDecimal bigDecimal = new BigDecimal(0.11D);/<code>

正例:

<code>// BigDecimal 正例BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);/<code>

十三、返回空數組和集合而非 null

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

反例:

<code>//返回null 反例public static Result[] getResults() {    return null;}public static List<result> getResultList() {    return null;}public static Map<string> getResultMap() {    return null;}/<string>/<result>/<code>

正例:

<code>//返回空數組和空集正例public static Result[] getResults() {    return new Result[0];}public static List<result> getResultList() {    return Collections.emptyList();}public static Map<string> getResultMap() {    return Collections.emptyMap();}/<string>/<result>/<code>

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

對象的equals 方法容易拋空指針異常,應使用常量或確定有值的對象來調用equals 方法。

反例:

<code>//調用 equals 方法反例private static boolean fileReader(String fileName)throws IOException{ // 可能拋空指針異常 return fileName.equals("Charming");}/<code>

正例:

<code>//調用 equals 方法正例private static boolean fileReader(String fileName)throws IOException{    // 使用常量或確定有值的對象來調用 equals 方法    return "Charming".equals(fileName);    //或使用:java.util.Objects.equals() 方法   return Objects.equals("Charming",fileName);}/<code>

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

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

反例:

<code>public enum SwitchStatus {    // 枚舉的屬性字段反例    DISABLED(0, "禁用"),    ENABLED(1, "啟用");    public int value;    private String description;    private SwitchStatus(int value, String description) {        this.value = value;        this.description = description;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }}/<code>

正例:

<code>public enum SwitchStatus {    // 枚舉的屬性字段正例    DISABLED(0, "禁用"),    ENABLED(1, "啟用");    // final 修飾    private final int value;    private final String description;    private SwitchStatus(int value, String description) {        this.value = value;        this.description = description;    }    // 沒有Setter 方法    public int getValue() {        return value;    }    public String getDescription() {        return description;    }}/<code>

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

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

反例:

<code>// String.split(String regex) 反例String[] split = "a.ab.abc".split(".");System.out.println(Arrays.toString(split));   // 結果為[]String[] split1 = "a|ab|abc".split("|");System.out.println(Arrays.toString(split1));  // 結果為["a", "|", "a", "b", "|", "a", "b", "c"]/<code>

正例:

<code>// String.split(String regex) 正例// . 需要轉譯String[] split2 = "a.ab.abc".split("\\\\.");System.out.println(Arrays.toString(split2));  // 結果為["a", "ab", "abc"]// | 需要轉譯String[] split3 = "a|ab|abc".split("\\\\|");System.out.println(Arrays.toString(split3));  // 結果為["a", "ab", "abc"]/<code>


分享到:


相關文章: