以下文章来源方志朋的博客,回复”666“获面试宝典

作者 | 涛姐涛哥

链接 | cnblogs.com/taojietaoge/p/11575376.html

如何更规范化编写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 取值性能更佳。

反例:

//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)。O(1)纬度减少循环次数 例子

反例:

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 编译器无法进行优化,所以要手动使用StringBuildersb.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";}*/}
}

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

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

反例:

//把其它对象或类型转化为字符串反例:int num = 520;// "" + valueString strLove = "" + num;

正例:

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

十二、避免使用BigDecimal(double)

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

反例:

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

正例:

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

图1. 失去精度

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

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

反例:

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

正例:

//返回空数组和空集正例
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();
}

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

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

反例:

 //调用 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);}

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

枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改;理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的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;}// 没有Setter 方法public int getValue() {return value;}public String getDescription() {return description;}
}

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

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

反例:

 // 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"]

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

热门内容:再见Spring!下一个开源框架更香!
Spring发布新成员:Spring GraphQL!高调出场的GraphQL能火起来了吗?
很哇塞的Java系列实战项目!
翻车!在项目中用了Arrays.asList、ArrayList的subList,被公开批评60岁还在写代码的开发者,他的建议或许正是你现在焦虑的根源!尝试改变一下吧!
最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

明天见(。・ω・。)ノ♡

16 条 yyds 的代码规范相关推荐

  1. Java技术:收集16 条 yyds 的代码规范,值得一读!

    今天给大家分享关于Java技术中16 条 yyds 的代码规范,读完肯定会有帮助! 一.MyBatis 不要为了多个查询条件而写 1 = 1 当遇到多个查询条件,使用where 1=1 可以很方便的解 ...

  2. 代码规范---16条代码规范

    代码规范-16条代码规范 1. MyBatis 不要为了多个查询条件而写 1 = 1 当遇到多个查询条件,使用where 1=1 可以很方便的解决我们的问题,但是这样很可能会造成非常大的性能损失,因为 ...

  3. 如何提升代码可读性?阿里发布16条设计规约

    脍炙人口的唐诗"两个黄鹂鸣翠柳,一行白鹭上青天",清爽直接,简明易懂.可读性好的代码也是让人陶醉的,那么如何写出可读性的代码? 近期,<阿里巴巴Java开发手册>推出详 ...

  4. 代码规范之华为公司代码规范

    华为公司代码规范 转于http://blog.sina.com.cn/s/blog_61176a740100ffer.html 内容简要:写代码习惯以及注释的要求. 1-1:程序块要采用缩进风格编写, ...

  5. 嵌入式C语言代码规范

    C语言代码规范 参考安富莱C语言编码规范 1.文件与目录 1.文件及目录的命名规定可用的字符集是[A-Z:a-z:0-9:._-]. 2.源文件名后缀用小写字母 .c 和.h. 3.文件的命名要准确清 ...

  6. 新增16条设计规约!阿里巴巴Java开发手册(详尽版)开放下载!

    2019独角兽企业重金招聘Python工程师标准>>> <阿里巴巴Java开发手册>是阿里内部Java工程师所遵循的开发规范,涵盖编程规约.单元测试规约.异常日志规约.M ...

  7. 《阿里巴巴JAVA开发手册》发布详尽版,新增16条设计规约

    2018年6月5日,<阿里巴巴Java开发手册>再次升级代码规范,新增了16条设计规约! <阿里巴巴Java开发手册>是阿里内部Java工程师所遵循的开发规范,涵盖编程规约.单 ...

  8. 现代软件工程讲义 3 代码规范与代码复审

    请参考原址:http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html 第10章 代码规范与代码复审 在第9章中,同学们完成了WC程序,经过 ...

  9. 解读阿里官方代码规范

    2017年开春,阿里对外公布了「阿里巴巴Java开发手册」从头到尾浏览了一遍这份手册之后,感觉很棒.虽然其中的某些观点笔者不能苟同,但大部分的规范还是值得绝大多数程序员学习和遵守的. 笔者将对这份代码 ...

最新文章

  1. 缓冲区和数组的输入输出问题
  2. CentOS - 修改主机名教程(将 localhost.localdomain 改成其它名字)
  3. django中使用原生sql
  4. 【干货】小米用户画像实战.pdf(附下载链接)
  5. cuda11+pytorch安装
  6. source ./ 和 . 的区别
  7. 如何通过一个字符串来实例化一个类_Spring官网阅读(一)容器及实例化
  8. 2021年11月_IEEE TRANSACTIONS ON MEDICAL IMAGING_科技前言热点调研表
  9. freeradius mysql nas_freeradius+mysql+交换机认证
  10. 电商平台日志分析系统(大数据) 上(不完整-版本不对应)
  11. PACS系统源码 影像管理系统源码(PACS)
  12. GitHub 上受欢迎的 Android UI Library 整理(一)
  13. uniapp对接腾讯即时通讯TIM 发图片消息问题
  14. linux ubantu snmp服务,ubuntu 20.04 snmp安装配置
  15. 禁止Altium designer(其他软件同样适用)联网的配置操作
  16. [技术讨论]关于单片机延时的实现讨论
  17. python kivy显示图片_Kivy 图形界面开发初体验
  18. 树莓派python驱动PCA9685
  19. 实验9 人口预测与数据拟合(最小二乘法)
  20. 《内网安全攻防:渗透测试实战指南》读书笔记(一):内网渗透测试基础

热门文章

  1. count http://www.cplusplus.com/reference/algorithm/count/
  2. SPOJ ATOMS - Atoms in the Lab
  3. [WCF] - Odata Service 访问失败,查看具体错误信息的方法
  4. 【转】学习汇编前你应该知道的知识
  5. 分布式技术一周技术动态 2016-11-27
  6. 最近最近在微软的Mobile Soft factory
  7. 中国电子学会青少年编程能力等级测试图形化四级编程题:正话反说
  8. 【怎样写代码】实现对象的复用 -- 享元模式(四):享元模式与字符串
  9. 【ACM】杭电OJ 2064(汉诺塔III)
  10. c语言将字母与数字分开存放,2017年计算机二级《C语言》考前提分试题及答案9...