五年工作经验总结 16 条的代码规范
如何更规范化编写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 count(*) from t_rule_BookInfo t where 1=1AND title = #{title}AND author = #{author}
正例:
select count(*) from t_rule_BookInfo ttitle = #{title}AND author = #{author}
UPDATE 操作也一样,可以用
二、 迭代entrySet() 获取Map 的key 和value
当循环中只需要获取Map 的主键key时,迭代keySet() 是正确的;但是,当需要主键key 和取值value 时,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通过get 取值性能更佳。
反例:
//Map 获取value 反例:HashMapmap = new HashMap<>(); for (String key : map.keySet()){String value = map.get(key);}
正例:
//Map 获取key & value 正例:HashMapmap = new HashMap<>(); for (Map.Entryentry : map.entrySet()){ String key = entry.getKey();String value = entry.getValue();}
三、使用Collection.isEmpty() 检测空
使用Collection.size() 来检测是否为空在逻辑上没有问题,但是使用Collection.isEmpty() 使得代码更易读,并且可以获得更好的性能;除此之外,任何Collection.isEmpty() 实现的时间复杂度都是O(1) ,不需要多次循环遍历,但是某些通过Collection.size() 方法实现的时间复杂度可能是O(n)。O(1)纬度减少循环次数 例子
反例:
LinkedListif (collection.size() == 0){System.out.println("collection is empty.");}
正例:
LinkedListif (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};Listlist = new ArrayList<>(); for (int i : arr){list.add(i);}
//初始化list,往list 中添加元素正例:int[] arr = new int[]{1,2,3,4};//指定集合list 的容量大小Listlist = new ArrayList<>(arr.length); for (int i : arr){list.add(i);}
//在循环中拼接字符串反例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 编译器无法进行优化,所以要手动使用StringBuildersb.append(i);}
//频繁调用Collection.contains() 反例Listfor (int i = 0; i <= Integer.MAX_VALUE; i++){//时间复杂度为O(n)if (list.contains(i))System.out.println("list contains "+ i);}
//频繁调用Collection.contains() 正例ListSetfor (int i = 0; i <= Integer.MAX_VALUE; i++){//时间复杂度为O(1)if (set.contains(i)){System.out.println("list contains "+ i);}}
//赋值静态成员变量反例private static Mapmap = new HashMap (){ {map.put("Leo",1);map.put("Family-loving",2);map.put("Cold on the out side passionate on the inside",3);}};private static Listlist = new ArrayList<>(){ {list.add("Sagittarius");list.add("Charming");list.add("Perfectionist");}};
//赋值静态成员变量正例private static Mapmap = new HashMap (); static {map.put("Leo",1);map.put("Family-loving",2);map.put("Cold on the out side passionate on the inside",3);}private static Listlist = new ArrayList<>(); static {list.add("Sagittarius");list.add("Charming");list.add("Perfectionist");}
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();}
//多余异常反例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";}*/}}
//把其它对象或类型转化为字符串反例:int num = 520;// "" + valueString strLove = "" + num;
//把其它对象或类型转化为字符串正例:int num = 520;// String.valueOf() 效率更高String strLove = String.valueOf(num);
// BigDecimal 反例BigDecimal bigDecimal = new BigDecimal(0.11D);
// BigDecimal 正例BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

//返回null 反例public static Result[] getResults() {return null;}public static ListgetResultList() { return null;}public static MapgetResultMap() { return null;}
//返回空数组和空集正例public static Result[] getResults() {return new Result[0];}public static ListgetResultList() { return Collections.emptyList();}public static MapgetResultMap() { return Collections.emptyMap();}
//调用 equals 方法反例private static boolean fileReader(String fileName)throws IOException{// 可能抛空指针异常return fileName.equals("Charming");}
//调用 equals 方法正例private static boolean fileReader(String fileName)throws IOException{// 使用常量或确定有值的对象来调用 equals 方法return "Charming".equals(fileName);//或使用:java.util.Objects.equals() 方法return Objects.equals("Charming",fileName);}
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;}// 没有Setter 方法public int getValue() {return value;}public String getDescription() {return description;}}
// 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"]
// 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"]

最近热文阅读:
1、为什么我劝你放弃了Restful API? 2、Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合 3、公司规定所有接口都用 POST请求,这是为什么? 4、为什么阿里强制 boolean 类型变量不能使用 is 开头? 5、面试官:InnoDB中一棵B+树可以存放多少行数据? 6、MyBatis批量插入几千条数据,请慎用foreach 7、有了 for (;;) ,为什么还需要while (true) ?到底哪个更快? 8、名企公开挂“加班真好”标语,员工称一年被免费“白嫖”600多小时!网友看不下去了,稽查部门展开调查... 9、面试官:为什么 Java 不把基本类型放在堆中?我竟然答不上来。。 10、IDEA 注释模板这样搞! 关注公众号,你想要的Java都在这里
