背景:如何更規(guī)范化編寫(xiě)Java代碼的重要性想必毋需多言,其中最重要的幾點(diǎn)當(dāng)屬提高代碼性能、使代碼遠(yuǎn)離Bug、令代碼更優(yōu)雅。
一、MyBatis不要為了多個(gè)查詢(xún)條件而寫(xiě)1=1
當(dāng)遇到多個(gè)查詢(xún)條件,使用where 1=1 可以很方便的解決我們的問(wèn)題,但是這樣很可能會(huì)造成非常大的性能損失,因?yàn)樘砑恿?“where 1=1 ”的過(guò)濾條件之后,數(shù)據(jù)庫(kù)系統(tǒng)就無(wú)法使用索引等查詢(xún)優(yōu)化策略,數(shù)據(jù)庫(kù)系統(tǒng)將會(huì)被迫對(duì)每行數(shù)據(jù)進(jìn)行掃描(即全表掃描) 以比較此行是否滿(mǎn)足過(guò)濾條件,當(dāng)表中的數(shù)據(jù)量較大時(shí)查詢(xún)速度會(huì)非常慢;此外,還會(huì)存在SQL 注入的風(fēng)險(xiǎn)。
反例:
《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》 標(biāo)記代替 1=1。
二、迭代entrySet()獲取Map的key和value
當(dāng)循環(huán)中只需要獲取Map 的主鍵key時(shí),迭代keySet() 是正確的;但是,當(dāng)需要主鍵key 和取值value 時(shí),迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通過(guò)get 取值性能更佳。
反例:
//Map 獲取value 反例:HashMap《String, String》 map = new HashMap《》();for (String key : map.keySet()){String value = map.get(key);}
正例:
//Map 獲取key & value 正例:HashMap《String, String》 map = new HashMap《》(); for (Map.Entry《String,String》 entry : map.entrySet()){ String key = entry.getKey(); String value = entry.getValue();}
三、使用Collection.isEmpty()檢測(cè)空
使用Collection.size() 來(lái)檢測(cè)是否為空在邏輯上沒(méi)有問(wèn)題,但是使用Collection.isEmpty() 使得代碼更易讀,并且可以獲得更好的性能;除此之外,任何Collection.isEmpty() 實(shí)現(xiàn)的時(shí)間復(fù)雜度都是O(1) ,不需要多次循環(huán)遍歷,但是某些通過(guò)Collection.size() 方法實(shí)現(xiàn)的時(shí)間復(fù)雜度可能是O(n)。O(1)緯度減少循環(huán)次數(shù)例子。
反例:
LinkedList《Object》 collection = new LinkedList《》();if (collection.size() == 0){ System.out.println(“collection is empty.”); }
正例:
LinkedList《Object》 collection = new LinkedList《》(); if (collection.isEmpty()){ System.out.println(“collection is empty.”); }
//檢測(cè)是否為null 可以使用CollectionUtils.isEmpty() if (CollectionUtils.isEmpty(collection)){ System.out.println(“collection is null.”);
}
四、初始化集合時(shí)盡量指定其大小
盡量在初始化時(shí)指定集合的大小,能有效減少集合的擴(kuò)容次數(shù),因?yàn)榧厦看螖U(kuò)容的時(shí)間復(fù)雜度很可能時(shí)O(n),耗費(fèi)時(shí)間和性能。
反例:
//初始化list,往list 中添加元素反例:int[] arr = new int[]{1,2,3,4};List《Integer》 list = new ArrayList《》();for (int i : arr){ list.add(i);}
正例:
//初始化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); }
五、使用StringBuilder拼接字符串
一般的字符串拼接在編譯期Java 會(huì)對(duì)其進(jìn)行優(yōu)化,但是在循環(huán)中字符串的拼接Java 編譯期無(wú)法執(zhí)行優(yōu)化,所以需要使用StringBuilder 進(jìn)行替換。
反例:
//在循環(huán)中拼接字符串反例String str = “”;for (int i = 0; i 《 10; i++){ //在循環(huán)中字符串拼接Java 不會(huì)對(duì)其進(jìn)行優(yōu)化 str += i;}
正例:
//在循環(huán)中拼接字符串正例 String str1 = “Love”; String str2 = “Courage”; String strConcat = str1 + str2; //Java 編譯器會(huì)對(duì)該普通模式的字符串拼接進(jìn)行優(yōu)化 StringBuilder sb = new StringBuilder(); for (int i = 0; i 《 10; i++){ //在循環(huán)中,Java 編譯器無(wú)法進(jìn)行優(yōu)化,所以要手動(dòng)使用StringBuilder sb.append(i); }
六、若需頻繁調(diào)用Collection.contains方法則使用Set
在Java 集合類(lèi)庫(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)。
反例:
//頻繁調(diào)用Collection.contains() 反例List《Object》 list = new ArrayList《》();for (int i = 0; i 《= Integer.MAX_VALUE; i++){ //時(shí)間復(fù)雜度為O(n) if (list.contains(i)) System.out.println(“l(fā)ist contains ”+ i); }
正例:
//頻繁調(diào)用Collection.contains() 正例 List《Object》 list = new ArrayList《》(); Set《Object》 set = new HashSet《》(); for (int i = 0; i 《= Integer.MAX_VALUE; i++){ //時(shí)間復(fù)雜度為O(1) if (set.contains(i)){ System.out.println(“l(fā)ist contains ”+ i); } }
七、使用靜態(tài)代碼塊實(shí)現(xiàn)賦值靜態(tài)成員變量
對(duì)于集合類(lèi)型的靜態(tài)成員變量,應(yīng)該使用靜態(tài)代碼塊賦值,而不是使用集合實(shí)現(xiàn)來(lái)賦值。
反例:
//賦值靜態(tài)成員變量反例 private static Map《String, Integer》 map = new HashMap《String, Integer》(){ { 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”); } };
正例:
//賦值靜態(tài)成員變量正例private static Map《String, Integer》 map = new HashMap《String, Integer》(); 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”); }
八、刪除未使用的局部變量、方法參數(shù)、私有方法、字段和多余的括號(hào)。
九、工具類(lèi)中屏蔽構(gòu)造函數(shù)
工具類(lèi)是一堆靜態(tài)字段和函數(shù)的集合,其不應(yīng)該被實(shí)例化;但是,Java 為每個(gè)沒(méi)有明確定義構(gòu)造函數(shù)的類(lèi)添加了一個(gè)隱式公有構(gòu)造函數(shù),為了避免不必要的實(shí)例化,應(yīng)該顯式定義私有構(gòu)造函數(shù)來(lái)屏蔽這個(gè)隱式公有構(gòu)造函數(shù)。
反例:
public class PasswordUtils { //工具類(lèi)構(gòu)造函數(shù)反例 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(); }
正例:
public class PasswordUtils { //工具類(lèi)構(gòu)造函數(shù)正例 private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
//定義私有構(gòu)造函數(shù)來(lái)屏蔽這個(gè)隱式公有構(gòu)造函數(shù) private PasswordUtils(){}
public static final String DEFAULT_CRYPT_ALGO = “PBEWithMD5AndDES”;
public static String encryptPassword(String aPassword) throws IOException { return new PasswordUtils(aPassword).encrypt(); }
十、刪除多余的異常捕獲并拋出
用catch 語(yǔ)句捕獲異常后,若什么也不進(jìn)行處理,就只是讓異常重新拋出,這跟不捕獲異常的效果一樣,可以刪除這塊代碼或添加別的處理。
反例:
//多余異常反例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) { //僅僅是重復(fù)拋異常 未作任何處理 throw e; }}
正例:
//多余異常正例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”; }*/ }}
十一、字符串轉(zhuǎn)化使用String.valueOf(value)代替“”+value
把其它對(duì)象或類(lèi)型轉(zhuǎn)化為字符串時(shí),使用String.valueOf(value) 比 “”+value 的效率更高。
反例:
//把其它對(duì)象或類(lèi)型轉(zhuǎn)化為字符串反例:int num = 520;// “” + valueString strLove = “” + num;
正例:
//把其它對(duì)象或類(lèi)型轉(zhuǎn)化為字符串正例:int num = 520;// String.valueOf() 效率更高String strLove = String.valueOf(num);
十二、避免使用BigDecimal(double)
BigDecimal(double) 存在精度損失風(fēng)險(xiǎn),在精確計(jì)算或值比較的場(chǎng)景中可能會(huì)導(dǎo)致業(yè)務(wù)邏輯異常。
反例:
// BigDecimal 反例BigDecimal bigDecimal = new BigDecimal(0.11D);
正例:
// BigDecimal 正例BigDecimal bigDecimal1 = 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 的語(yǔ)句使代碼更簡(jiǎn)潔。
反例:
//返回null 反例public static Result[] getResults() { return null;}
public static List《Result》 getResultList() { return null;}
public static Map《String, Result》 getResultMap() { return null;}
正例:
//返回空數(shù)組和空集正例public static Result[] getResults() { return new Result[0];}
public static List《Result》 getResultList() { return Collections.emptyList();}
public static Map《String, Result》 getResultMap() { return Collections.emptyMap();}
十四、優(yōu)先使用常量或確定值調(diào)用equals方法
對(duì)象的equals 方法容易拋空指針異常,應(yīng)使用常量或確定有值的對(duì)象來(lái)調(diào)用equals 方法。
反例:
//調(diào)用 equals 方法反例private static boolean fileReader(String fileName)throws IOException{ // 可能拋空指針異常 return fileName.equals(“Charming”); }
正例:
//調(diào)用 equals 方法正例private static boolean fileReader(String fileName)throws IOException{
// 使用常量或確定有值的對(duì)象來(lái)調(diào)用 equals 方法 return “Charming”.equals(fileName);
//或使用:java.util.Objects.equals() 方法 return Objects.equals(“Charming”,fileName); }
十五、枚舉的屬性字段必須是私有且不可變
枚舉通常被當(dāng)做常量使用,如果枚舉中存在公共屬性字段或設(shè)置字段方法,那么這些枚舉常量的屬性很容易被修改;理想情況下,枚舉中的屬性字段是私有的,并在私有構(gòu)造函數(shù)中賦值,沒(méi)有對(duì)應(yīng)的Setter 方法,最好加上final 修飾符。
反例:
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; }}
正例:
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; }
// 沒(méi)有Setter 方法 public int getValue() { return value; }
public String getDescription() { return description; }}
十六、tring.split(String regex)部分關(guān)鍵字需要轉(zhuǎn)譯
使用字符串String 的plit 方法時(shí),傳入的分隔字符串是正則表達(dá)式,則部分關(guān)鍵字(比如 。[]()| 等)需要轉(zhuǎn)義。
反例:
// String.split(String regex) 反例String[] split = “a.ab.abc”.split(“。”);System.out.println(Arrays.toString(split)); // 結(jié)果為[]String[] split1 = “a|ab|abc”.split(“|”);System.out.println(Arrays.toString(split1)); // 結(jié)果為[“a”, “|”, “a”, “b”, “|”, “a”, “b”, “c”]
正例:
// String.split(String regex) 正例// 。 需要轉(zhuǎn)譯String[] split2 = “a.ab.abc”.split(“\。”);System.out.println(Arrays.toString(split2)); // 結(jié)果為[“a”, “ab”, “abc”]
// | 需要轉(zhuǎn)譯String[] split3 = “a|ab|abc”.split(“\|”);System.out.println(Arrays.toString(split3)); // 結(jié)果為[“a”, “ab”, “abc”]
END
作者:濤姐濤哥來(lái)源:cnblogs.com/taojietaoge/p/11575376.html
版權(quán)歸原作者所有,如有侵權(quán),請(qǐng)聯(lián)系刪除。
編輯:jq
-
JAVA
+關(guān)注
關(guān)注
20文章
2984瀏覽量
106869 -
代碼
+關(guān)注
關(guān)注
30文章
4886瀏覽量
70257 -
Value
+關(guān)注
關(guān)注
0文章
11瀏覽量
8793 -
mybatis
+關(guān)注
關(guān)注
0文章
63瀏覽量
6870
原文標(biāo)題:16條yyds的代碼規(guī)范
文章出處:【微信號(hào):pcbgood,微信公眾號(hào):奈因PCB電路板設(shè)計(jì)】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
【JVM開(kāi)發(fā)者必看】IntelliJ IDEA代碼分析實(shí)踐指南:實(shí)時(shí)糾錯(cuò)、冗余檢測(cè)、自動(dòng)修復(fù)等

分析C語(yǔ)言代碼結(jié)構(gòu)的設(shè)計(jì)問(wèn)題
低代碼與傳統(tǒng)開(kāi)發(fā)的區(qū)別 低代碼與無(wú)代碼開(kāi)發(fā)的區(qū)別
如何在日常開(kāi)發(fā)過(guò)程中提高代碼質(zhì)量

如何提高嵌入式代碼質(zhì)量?
讓單片機(jī)代碼性能起飛的七大技巧

昂洋科技談國(guó)巨貼片電阻的尺寸代碼和選購(gòu)

怎么樣提高verilog代碼編寫(xiě)水平?
代碼整潔之道-大師眼中的整潔代碼是什么樣

軟件設(shè)計(jì)哲學(xué):新“代碼整潔之道”

國(guó)內(nèi)低代碼平臺(tái)推薦--萬(wàn)界星空科技低代碼平臺(tái)

該如何提高代碼容錯(cuò)率、降低代碼耦合度?

評(píng)論