如何更规范化编写Java 代码

如何更规范化编写Java 代码

 

Many of the happiest people are those who own the least. But are we really so happy with our IPhones, our big houses, our fancy cars?

忘川如斯,拥有一切的人才更怕失去。

 

背景:如何更规范化编写Java 代码的重要性想必毋需多言,其中最重要的几点当属提高代码性能、使代码远离Bug、令代码更优雅。

一、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 操作也一样,可以用<set> 标记代替 1=1。

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

      当循环中只需要获取Map 的主键key时,迭代keySet() 是正确的;但是,当需要主键key 和取值value 时,迭代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);
5         }

正例:

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

三、使用Collection.isEmpty() 检测空

      使用Collection.size() 来检测是否为空在逻辑上没有问题,但是使用Collection.isEmpty() 使得代码更易读,并且可以获得更好的性能;除此之外,任何Collection.isEmpty() 实现的时间复杂度都是O(1) ,不需要多次循环遍历,但是某些通过Collection.size() 方法实现的时间复杂度可能是O(n)。O(1)纬度减少循环次数 例子

反例:

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

正例:

 1  LinkedList<Object> collection = new LinkedList<>();
 2         if (collection.isEmpty()){
 3             System.out.println("collection is empty.");
 4         }
 5         
 6         //检测是否为null 可以使用CollectionUtils.isEmpty()
 7         if (CollectionUtils.isEmpty(collection)){
 8             System.out.println("collection is null.");
 9 
10         }

四、初始化集合时尽量指定其大小

      尽量在初始化时指定集合的大小,能有效减少集合的扩容次数,因为集合每次扩容的时间复杂度很可能时O(n),耗费时间和性能。

反例:

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

正例:

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

五、使用StringBuilder 拼接字符串

      一般的字符串拼接在编译期Java 会对其进行优化,但是在循环中字符串的拼接Java 编译期无法执行优化,所以需要使用StringBuilder 进行替换。

反例:

1  //在循环中拼接字符串反例
2        String str = "";
3        for (int i = 0; i < 10; i++){
4            //在循环中字符串拼接Java 不会对其进行优化
5            str += i;
6        }

正例:

1   //在循环中拼接字符串正例
2        String str1 = "Love";
3        String str2 = "Courage";
4        String strConcat = str1 + str2;  //Java 编译器会对该普通模式的字符串拼接进行优化
5         StringBuilder sb = new StringBuilder();
6         for (int i = 0; i < 10; i++){
7            //在循环中,Java 编译器无法进行优化,所以要手动使用StringBuilder
8             sb.append(i);
9         }

 六、若需频繁调用Collection.contains 方法则使用Set

      在Java 集合类库中,List的contains 方法普遍时间复杂度为O(n),若代码中需要频繁调用contains 方法查找数据则先将集合list 转换成HashSet 实现,将O(n) 的时间复杂度将为O(1)。

反例:

1 //频繁调用Collection.contains() 反例
2         List<Object> list = new ArrayList<>();
3         for (int i = 0; i <= Integer.MAX_VALUE; i++){
4             //时间复杂度为O(n)
5             if (list.contains(i))
6             System.out.println("list contains "+ i);
7         }

正例:

1 //频繁调用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             //时间复杂度为O(1)
6             if (set.contains(i)){
7                 System.out.println("list contains "+ i);
8             }
9         }

七、使用静态代码块实现赋值静态成员变量

      对于集合类型的静态成员变量,应该使用静态代码块赋值,而不是使用集合实现来赋值。

反例:

 1 //赋值静态成员变量反例
 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  //赋值静态成员变量正例
 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         
 9     private static List<String> list = new ArrayList<>();
10         static {
11             list.add("Sagittarius");
12             list.add("Charming");
13             list.add("Perfectionist");
14         }

八、删除未使用的局部变量、方法参数、私有方法、字段和多余的括号

九、工具类中屏蔽构造函数

      工具类是一堆静态字段和函数的集合,其不应该被实例化;但是,Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数,为了避免不必要的实例化,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。

反例:

1 public class PasswordUtils {
2     //工具类构造函数反例
3     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
4 
5     public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
6 
7     public static String encryptPassword(String aPassword) throws IOException {
8         return new PasswordUtils(aPassword).encrypt();
9     }

正例:

 1 public class PasswordUtils {
 2     //工具类构造函数正例
 3     private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
 4 
 5     //定义私有构造函数来屏蔽这个隐式公有构造函数
 6     private PasswordUtils(){}
 7     
 8     public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
 9 
10     public static String encryptPassword(String aPassword) throws IOException {
11         return new PasswordUtils(aPassword).encrypt();
12     }

十、删除多余的异常捕获并抛出

      用catch 语句捕获异常后,若什么也不进行处理,就只是让异常重新抛出,这跟不捕获异常的效果一样,可以删除这块代码或添加别的处理。

反例:

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

正例:

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

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

      把其它对象或类型转化为字符串时,使用String.valueOf(value) 比 ""+value 的效率更高。

反例:

1 //把其它对象或类型转化为字符串反例:
2             int num = 520;
3             // "" + value
4             String strLove = "" + num;

正例:

1 //把其它对象或类型转化为字符串正例:
2             int num = 520;
3             // String.valueOf() 效率更高
4             String strLove = String.valueOf(num);

十二、避免使用BigDecimal(double)

      BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。

反例:

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

正例:

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

图1. BigDecimal 精度丢失

十三、返回空数组和集合而非 null

      若程序运行返回null,需要调用方强制检测null,否则就会抛出空指针异常;返回空数组或空集合,有效地避免了调用方因为未检测null 而抛出空指针异常的情况,还可以删除调用方检测null 的语句使代码更简洁。

反例:

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

正例:

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

十四、优先使用常量或确定值调用equals 方法

      对象的equals 方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals 方法。

反例:

1 //调用 equals 方法反例
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // 可能抛空指针异常
5         return fileName.equals("Charming");
6  }

正例:

1 //调用 equals 方法正例
2     private static boolean fileReader(String fileName)throws IOException{
3 
4         // 使用常量或确定有值的对象来调用 equals 方法
5         return "Charming".equals(fileName);
6         
7         //或使用: java.util.Objects.equals() 方法
8        return Objects.equals("Charming",fileName);
9  }

十五、枚举的属性字段必须是私有且不可变

      枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改;理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的Setter 方法,最好加上final 修饰符。

反例:

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

正例:

 1 public enum SwitchStatus {
 2     // 枚举的属性字段正例
 3     DISABLED(0, "禁用"),
 4     ENABLED(1, "启用");
 5 
 6     // final 修饰
 7     private final int value;
 8     private final String description;
 9 
10     private SwitchStatus(int value, String description) {
11         this.value = value;
12         this.description = description;
13     }
14 
15     // 没有Setter 方法
16     public int getValue() {
17         return value;
18     }
19 
20     public String getDescription() {
21         return description;
22     }
23 }

十六、tring.split(String regex)部分关键字需要转译

      使用字符串String 的plit 方法时,传入的分隔字符串是正则表达式,则部分关键字(比如 .[]()\| 等)需要转义。

反例:

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

正例:

1  // String.split(String regex) 正例
2         // . 需要转译
3         String[] split2 = "a.ab.abc".split("\\.");
4         System.out.println(Arrays.toString(split2));  // 结果为["a", "ab", "abc"]
5 
6         // | 需要转译
7         String[] split3 = "a|ab|abc".split("\\|");
8         System.out.println(Arrays.toString(split3));  // 结果为["a", "ab", "abc"]

图2. String.split(String regex) 正反例

 

 

拥有一切的人才更怕失去

 

 

posted @ 2019-09-26 23:36  涛姐涛哥  阅读(2815)  评论(6编辑  收藏  举报