转自:http://blog.lichengwu.cn/java/2013/11/24/use-findbugs-code-review/java
Findbugs是一个代码静态分析工具,用来找出Java代码中的bug。经过分析字节码并与一组缺陷模式匹配,找出代码中的问题。 缓存
目前Findbugs支持除了java 8之外的全部版本编译的字节码文件分析。 安全
Findbugs不只提供了可视化界面,还有Idea,Eclipse插件。 less
Findbugs有谷歌和SUM/(Oracle)支持,在JDK源码编译中,依赖了Findbugs对JDK源码的检查。也就是说,虽然能够自由编译JDK,可是若是修改后的代码太烂,不能经过Findbugs的检查,同样不能经过编译。 eclipse
项目地址:http://findbugs.sourceforge.net/ ide
Findbugs支持命令行,ant,可视化界面和IDE插件方式运行,以IDEA的插件使用为例。 工具
Eclipse插件安装地址:http://findbugs.cs.umd.edu/eclipse/ oop
IDEA插件安装地址:http://plugins.jetbrains.com/plugin/3847 性能
在Findbugs中能找到下面类型的bug(有些不算是bug,应该说是很差的实践)。 .net
Cateory
Number
Samples
Correctness
142
Illegal format string
Null value is guaranteed to be dereferenced
Call to equals() comparing unrelated class and interface
Bad practice
84
Confusing method names
Method may fail to close stream
Comparison of String parameter using == or !=
Dodgy code
71
Useless control flow
Integer remainder modulo 1
Redundant null check of value known to be null
Multithreaded Correctness
45
A thread was created using the default empty run method
Class's writeObject() method is synchronized but nothing else is
Performance
27
Method concatenates strings using + in a loop
Method invokes inefficient Boolean constructor
Malicious Code Vulnerability
15
Finalizer should be protected, not public
Field isn't final and can't be protected from malicious code
Security
11
Hardcoded constant database password
A prepared statement is generated from a variable String
Experimental
3
Method may fail to clean up stream or resource
Internationalization
2
Consider using Locale parameterized version of invoked method
低效的迭代器:
修改后:
for (Integer groupKey : groupList.keySet()) insertGroupedList(groupKey); }
装箱/拆箱0L
在java.lang.Long中是有缓存的,因此常量0L先拆箱成小long,而后赋值给agengId的时候装箱成大Long,两次操做就是没有必要的。
修改后:
agentId = (agentId == null) ? Long.valueOf(0) : agentId;
静态变量:
这个常量是在初始化的时候赋值的,在内存中没有必要存在多份,能够声明成static。
内部类,何不静态?
MuFlightInfoDO是MuFlightFareQuery的内部类,MuFlightInfoDO的实例保存了一份建立它的类(MuFlightFareQuery)的引用,这样不只使MuFlightInfoDO类占用更大的空间,并且是外部的MuFlightFareQuery生命周期更长了。
忽略异常:
集合使用removeAll来清理:
直接调用clear()或者是个bug?
流程:
else if里面有没任何代码,考虑删除。
集合:
hsfServices
声明成map:ConcurrentHashMap<String,HSFSpringConsumerBean hsfServices>
在这里hsfServices.contains(key)参数是String类型,可是声明的map是HSFSpringConsumerBean类型,应该永远不会返回true,应该是containsKey吧?
equal类型不匹配:
dfare.getAgentSupportType().equals(AgentSupportType.ONE) 左边Integer,右边enum。
DateFormat
DateFormat不是线程安装的,在这里声明为类成员,会有问题。
有些代码问题在人为的review的时候很难发现,若是上线了会有很大的隐患,虽然当时没有出现bug。利用Findbugs在提交代码的时候本身进行review。让你的代码出更少的bug。
Keep the bar green, keep you code clean.