目錄
一、MyBatis 不要為了多個查詢條件而寫 1 = 1
二、迭代entrySet() 獲取Map 的key 和value
三、使用Collection.isEmpty() 檢測空
四、初始化集合時盡量指定其大小
五、使用StringBuilder 拼接字串
六、若需頻繁呼叫Collection.contains 方法則使用Set
七、使用靜態代碼塊實作賦值靜態成員變數
八、洗掉未使用的區域變數、方法引數、私有方法、欄位和多余的括號,
九、工具類中屏蔽建構式
十、洗掉多余的例外捕獲并跑出
作業了幾個月,感覺自己代碼很不規范,有很多冗余,比較亂,請問怎么針對性的改善代碼規范?
下面分享一篇大佬的規范代碼實操,
代碼能夠寫成這樣 666 啊,大佬收徒嗎?

一、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 操作也一樣,可以用標記代替 1=1,
二、迭代entrySet() 獲取Map 的key 和value
當回圈中只需要獲取Map 的主鍵key時,迭代keySet() 是正確的;但是,當需要主鍵key 和取值value 時,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通過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() 檢測空
使用Collection.size() 來檢測是否為空在邏輯上沒有問題,但是使用Collection.isEmpty() 使得代碼更易讀,并且可以獲得更好的性能;除此之外,任何Collection.isEmpty() 實作的時間復雜度都是O(1) ,不需要多次回圈遍歷,但是某些通過Collection.size() 方法實作的時間復雜度可能是O(n)
反例:
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.");
}
//檢測是否為null 可以使用CollectionUtils.isEmpty()
if (CollectionUtils.isEmpty(collection)){
System.out.println("collection is null.");
}
四、初始化集合時盡量指定其大小
盡量在初始化時指定集合的大小,能有效減少集合的擴容次數,因為集合每次擴容的時間復雜度很可能時O(n),耗費時間和性能,
反例:
//初始化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 會對其進行優化,但是在回圈中字串的拼接Java 編譯期無法執行優化,所以需要使用StringBuilder 進行替換,
反例:
//在回圈中拼接字串反例
String str = "";
for (int i = 0; i < 10; i++){
//在回圈中字串拼接Java 不會對其進行優化
str += i;
}
正例:
//在回圈中拼接字串正例
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);
}
六、若需頻繁呼叫Collection.contains 方法則使用Set
在Java 集合類別庫中,List的contains 方法普遍時間復雜度為O(n),若代碼中需要頻繁呼叫contains 方法查找資料則先將集合list 轉換成HashSet 實作,將O(n) 的時間復雜度將為O(1),
反例:
//頻繁呼叫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);
}
正例:
//頻繁呼叫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);
}
}
七、使用靜態代碼塊實作賦值靜態成員變數
對于集合型別的靜態成員變數,應該使用靜態代碼塊賦值,而不是使用集合實作來賦值,
反例:
//賦值靜態成員變數反例
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");
}
};
正例:
//賦值靜態成員變數正例
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");
}
八、洗掉未使用的區域變數、方法引數、私有方法、欄位和多余的括號,
九、工具類中屏蔽建構式
工具類是一堆靜態欄位和函式的集合,其不應該被實體化;但是,Java 為每個沒有明確定義建構式的類添加了一個隱式公有建構式,為了避免不必要的實體化,應該顯式定義私有建構式來屏蔽這個隱式公有建構式,
反例:
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();
}
正例:
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();
}
十、洗掉多余的例外捕獲并跑出
用catch 陳述句捕獲例外后,若什么也不進行處理,就只是讓例外重新拋出,這跟不捕獲例外的效果一樣,可以洗掉這塊代碼或添加別的處理,
反例:
//多余例外反例
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;
}
}
正例:
//多余例外正例
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";
}*/
}
}
文章到這里就結束了
為了讓大家能夠更加規范的撰寫代碼,小編這里為大家準備了一份阿里巴巴開發手冊,需要的小伙伴們可以 點我 點我 免費領取哦

喜歡小編的分享可以點贊關注哦,小編持續為你分享最新文章 和 福利領取哦
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/197280.html
標籤:java
