1、".equals()" should not be used to test the values of "Atomic" classes.
bug 主要
不要使用equals方法對AtomicXXX進行是否相等的判斷
Atomic變量永遠只會和自身相等,Atomic變量沒有覆寫equals()方法.
2、"=+" should not be used instead of "+="
bug 主要
"=+" 與 "=+" 意義不同
a =+ b;雖然正確但寫法不合規,應寫成 a = +b;
3、"@NonNull" values should not be set to null
bug 次要
標注非空假定非空且在使用之前不進行非空檢查,設置為空會導致空指針異常
4、"BigDecimal(double)" should not be used
bug 主要
因為浮點的不精確,可能使用BigDecimal(double)得不到期望的值
5、"compareTo" results should not be checked for specific values
bug 次要
compareTo可能返回不是具體的值(除0外),建議用 >0、<0、=0
6、"compareTo" should not return "Integer.MIN_VALUE"
bug 次要
compareTo只代表一個不等標識,不代表不等的程度,應返回-1,0,1標識即可
7、"Double.longBitsToDouble" should not be used for "int"
bug 主要
Double.longBitsToDouble返回給定的位所代表的double值,需要一個64位的long類型參數.
8、 "equals" method overrides should accept "Object" parameters
bug 主要
equals作為方法名應該僅用於重寫Object.equals(Object)來避免混亂.
9、 "equals(Object obj)" should test argument type
bug 次要
要比較obj的class type是否一樣
10、"equals" methods should be symmetric and work for subclasses
bug 次要
equals應是對等並且在有子類參與時能正常工作
11、"equals(Object obj)" and "hashCode()" should be overridden in pairs
bug 次要
成對重寫
12、"Externalizable" classes should have no-arguments constructors
bug 主要
Externalizable(可序列化與返序列化)類應該有無參構造器
13、"getClass" should not be used for synchronization
bug 主要
{synchronized (this.getClass())} 錯誤 子類繼承此方法時不能做到同步
{synchronized (MyClass.class)} 正確
14、"hashCode" and "toString" should not be called on array instances
bug 主要
使用Arrays.toString(args)和Arrays.hashCode(args)代替.
15、"instanceof" operators that always return "true" or "false" should be removed
bug 主要
16、"InterruptedException" should not be ignored
bug 主要
try {
while (true) {
// do stuff
}
}catch (InterruptedException e) {
LOGGER.log(Level.WARN, "Interrupted!", e);
// Restore interrupted state...
Thread.currentThread().interrupt();
}
17、"Iterator.hasNext()" should not call "Iterator.next()"
bug 主要
18、"Iterator.next()" methods should throw "NoSuchElementException"
bug 次要
public String next(){
if(!hasNext()){
throw new NoSuchElementException();
}
...
}
19、"notifyAll" should be used
bug 主要
notify可能不能喚醒正確的線程,notifyAll代之。
20、"null" should not be used with "Optional"
bug 主要
把判空包裝起來使用而不直接使用!=null
21、"PreparedStatement" and "ResultSet" methods should be called with valid indices
bug 阻斷
PreparedStatement與ResultSet參數設置與獲取數據由序號1開始而非0
22、"read" and "readLine" return values should be used
bug 主要
BufferedReader.readLine(), Reader.read()及子類中的相關方法都應該先存儲再比較
buffReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = buffReader.readLine()) != null) {
// ...
}
23、"runFinalizersOnExit" should not be called
bug 嚴重
JVM退出時不可能運行finalizers,System.runFinalizersOnExit 和 Runtime.runFinalizersOnExit可以在jvm退出時運行但是因為他們不安全而棄用.
正確用法:
Runtime.addShutdownHook(new Runnable() {
public void run(){
doSomething();
}
});
24、"ScheduledThreadPoolExecutor" should not have 0 core threads
bug 嚴重
java.util.concurrent.ScheduledThreadPoolExecutor由屬性corePoolSize指定線程池大小,如果設置為0表示線程執行器無線程可用且不做任何事.
25、"Serializable" inner classes of non-serializable classes should be "static"
bug 次要
序列化非靜態內部類將導致嘗試序列化外部類,如果外部類不是序列化類,會產生運行時異常,內部類靜態化會避免這種情況
26、"SingleConnectionFactory" instances should be set to "reconnectOnException"
bug 主要
使用Spring SingleConnectionFactory而不啟用reconnectOnException設置當連接惡化將阻止自動連接恢復。
27、"StringBuilder" and "StringBuffer" should not be instantiated with a character
bug 主要
StringBuffer foo = new StringBuffer('x'); 錯 equivalent to StringBuffer foo = new StringBuffer(120);
StringBuffer foo = new StringBuffer("x"); 對
28、 "super.finalize()" should be called at the end of "Object.finalize()" implementations
bug 嚴重
protected void finalize() {
releaseSomeResources();
super.finalize(); //調用,最后調用
}
29、"toArray" should be passed an array of the proper type
bug 次要
toArray()無參且強制類型轉換會產生運行時異常,應傳入一個合適的類弄作參數
public String [] getStringArray(List<String> strings) {
return strings.toArray(new String[0]);
}
30、"toString()" and "clone()" methods should not return null
bug 主要
可返回""
31、 "wait" should not be called when multiple locks are held
bug 阻斷
32、 "wait", "notify" and "notifyAll" should only be called when a lock is obviously held on an object
bug 主要
先要獲得對象鎖才能進行上述操作
private void removeElement() {
synchronized(obj) {
while (!suitableCondition()){
obj.wait();
}
... // Perform removal
}
}
or
private synchronized void removeElement() {
while (!suitableCondition()){
wait();
}
... // Perform removal
}
33、"wait(...)" should be used instead of "Thread.sleep(...)" when a lock is held
bug 阻斷
當持有鎖的當前線程調用Thread.sleep(...)可能導致性能和擴展性問題,甚至死鎖因為持有鎖的當前線程已凍結.合適的做法是鎖對象wait()釋放鎖讓其它線程進來運行.
34、A "for" loop update clause should move the counter in the right direction
bug 主要
檢查for循環下標遞增或遞減正確
35、All branches in a conditional structure should not have exactly the same implementation
bug 主要
分支中不應該有相同的實現
36、Blocks should be synchronized on "private final" fields or parameters
bug 主要
synchronized同步塊應該鎖在private final fields或parameters對象上,因為同步塊內非final鎖對象可能改變導致其它線程進來運行.
37、Boxing and unboxing should not be immediately reversed
bug 次要
自動拆箱和裝箱不需手動轉換
38、Child class methods named for parent class methods should be overrides
bug 主要
以下情況不是重寫:
a、父類方法是static的而子類方法不是static的
b、子類方法的參數或返回值與父類方法不是同一個包
c、父類方法是private
為了不產生混亂,不要與父類方法同名
39、Classes extending java.lang.Thread should override the "run" method
bug 主要
線程類應該重寫run方法
40、Classes should not be compared by name
bug 主要
不要用類名稱比較類是否相同,而用instanceof或者Class.isAssignableFrom()進行底動類型比較
41、Classes that don't define "hashCode()" should not be used in hashes
bug 主要
沒有定義hashCode()方法的類不能作為hash集合中的鍵值,因為equal相同的實例對像可能返回不同的hash值.
42、Collections should not be passed as arguments to their own methods
bug 主要
集合實例不應該作為參數被傳給集合實你還自已的方法中
43、Conditionally executed blocks should be reachable
bug 主要
條件執行塊應該可達
44、Constructor injection should be used instead of field injection
bug 主要
構造器注入應該替代屬性注入(非Spring framework)
因為任何非Spring framework實例化而是通過構造器實例化的實例不能注入屬性,這樣公有的構造器實化化后可能產生NullPointerException,除非所有的構造器都是私有的
45、Consumed Stream pipelines should not be reused
bug 主要
流不應該重用
46、Custom resources should be closed
bug 阻斷
資源應該關閉
47、Custom serialization method signatures should meet requirements
bug 主要
自定義類序列化方法簽名應該合法
49、Dependencies should not have "system" scope
bug 嚴重
maven依賴不要在system scope
50、Dissimilar primitive wrappers should not be used with the ternary operator without explicit casting
bug 主要
不同的原始包裝類如果沒有明確的類轉換不能用於三元操作中
51、Double Brace Initialization should not be used
bug 次要
雙構造初始不要用
Map source = new HashMap(){{ // Noncompliant
put("firstName", "John");
put("lastName", "Smith");
}};
此操作如一個anonymous inner class,如果anonymous inner class返回且被其它對象引用,可能產生memory leaks,既使不產生memory leaks也會讓大多維護者感到迷惑
52、Double-checked locking should not be used
bug 阻斷
重復檢查的鎖塊不要使用
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
應
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
53、Equals Hash Code
bug 嚴重
成對重寫equals()與hashCode()
54、Exception should not be created without being thrown
bug 主要
不被拋出的異常不要創建
55、Expressions used in "assert" should not produce side effects
bug 主要
assert表達式不要產生負影響,不要改變數據狀態
56、Failed unit tests should be fixed
bug 主要
失敗的單元測試應該盡快解決掉
57、Floating point numbers should not be tested for equality
bug 主要
浮點數不要進行比較
58、Getters and setters should be synchronized in pairs
bug 主要
get與set應該成對進行同步操作
59、Identical expressions should not be used on both sides of a binary operator
bug 主要
相同的表達式不要作為二進制操作的操作數使用,應該簡化
60、Inappropriate "Collection" calls should not be made
bug 主要
正確使用集合元素類型
61、Inappropriate regular expressions should not be used
bug 主要
正確使用正則表達式
62、Intermediate Stream methods should not be left unused
bug 主要
中間流應該被使用
63、Ints and longs should not be shifted by zero or more than their number of bits-1
bug 次要
整型與長整型位移操作數應該價於1與類型占位數-1
64、Invalid "Date" values should not be used
bug 主要
正確使用日期
65、Jump statements should not occur in "finally" blocks
bug 主要
finally塊中使用return, break, throw等Jump statements,會阻止在try catch中拋出的未處理異常的傳播
66、Locks should be released
bug 嚴重
保證鎖的能夠釋放
67、Loop conditions should be true at least once
bug 主要
循環應該至少走一次
68、Loops should not be infinit
bug 阻斷
循環不應該死循環
69、Math operands should be cast before assignment
bug 次要
數字操作在操作或賦值前要轉化
70、Math should not be performed on floats
bug 次要
BigDecimal代替floats進行大數精確運算
71、Methods "wait(...)", "notify()" and "notifyAll()" should not be called on Thread instances
bug 阻斷
不要在線程中使用"wait(...)", "notify()" and "notifyAll()"
72、Methods should not be named "hashcode" or "equal"
bug 主要
除非Override重寫這些方法
73、Multiline blocks should be enclosed in curly braces
bug 主要
多列塊應用大括號括起來
74、Neither "Math.abs" nor negation should be used on numbers that could be "MIN_VALUE"
bug 次要
不要對數值類型的MIN_VALUE值或返回值為此值進行Math.abs與取反操作,因為不會起作用。
75、Non-public methods should not be "@Transactional"
bug 主要
非public方法不要注解Transactional,調用時spring 會拋出異常
76、Non-serializable classes should not be written
bug 主要
執行寫操作的類要序列化,否則會拋出異常
77、Non-serializable objects should not be stored in "HttpSession" objects
bug 主要
HttpSession要保存序列化的對象
78、Non-thread-safe fields should not be static
bug 主要
非線程安全的域不應該靜態化
79、Null pointers should not be dereferenced
bug 主要
空指針引用不應被訪問
80、Optional value should only be accessed after calling isPresent()
bug 主要
Optional實例值的獲取要isPresent()之后再做操作
90、Printf-style format strings should not lead to unexpected behavior at runtime
bug 阻斷
因為Printf風格格式化是在運行期解讀,而不是在編譯期檢驗,會存在風險
91、Raw byte values should not be used in bitwise operations in combination with shifts
bug 主要
原始字節值不應參與位運算
result = (result << 8) | readByte(); // Noncompliant
正:
result = (result << 8) | (readByte() & 0xff);
92、Reflection should not be used to check non-runtime annotations
bug 主要
反射操作不應該運於檢查非運行時注解
93、Related "if/else if" statements should not have the same condition
bug 主要
if/else if中不應該有相同的條件
94、Resources should be closed
bug 阻斷
打開的資源應該關閉並且放到finally塊中進行關閉
95、Return values from functions without side effects should not be ignored
bug 主要
操作對函數返回值沒有影響的應該忽略
public void handle(String command){
command.toLowerCase(); // Noncompliant; result of method thrown away
...
}
96、Servlets should not have mutable instance fields
bug 主要
servlet容器對每一個servlet創建一個實例導致實例變量共享產生問題
struts1.x 也是單例
97、Short-circuit logic should be used to prevent null pointer dereferences in conditionals
bug 主要
應正確使用短路邏輯來防止條件中的空指針引用訪問
98、Silly equality checks should not be made
bug 主要
愚蠢的相等檢查不應該做
非同類型的對象equal
99、Spring "@Controller" classes should not use "@Scope"
bug 主要
保持spring controller的單例
100、Synchronization should not be based on Strings or boxed primitives
bug 主要
字符串和封箱類不應該被用作鎖定對象,因為它們被合並和重用。
101、The non-serializable super class of a "Serializable" class should have a no-argument constructor
bug 次要
序列化的類的非序列化父類應有一個無參構造器
102、The Object.finalize() method should not be called
bug 主要
Object.finalize()不要人為去調用
103、The Object.finalize() method should not be overriden
bug 主要
Object.finalize()不要重寫
104、The signature of "finalize()" should match that of "Object.finalize()"
bug 主要
Object.finalize()不要重寫
105、The value returned from a stream read should be checked
bug 次要
從流中讀取的值應先檢查再操作
106、Thread.run() should not be called directly
bug 主要
調用start()
107、Useless "if(true) {...}" and "if(false){...}" blocks should be removed
bug 主要
無用的if(true)和if(false)塊應移除
108、Value-based classes should not be used for locking
bug 主要
基於值的類不要用於鎖對象
109、Value-based objects should not be serialized
bug 次要
基於值的對象不應被用於序列化
110、Values should not be uselessly incremented
bug 主要
值增減后不存儲是代碼浪費甚至是bug
111、Variables should not be self-assigned
bug 主要
變量不應該自分配如下:
public void setName(String name) {
name = name;
}
112、Week Year ("YYYY") should not be used for date formatting
bug 主要
日期格式化錯誤
113、Zero should not be a possible denominator
bug 嚴重
零不應該是一個可能的分母
114、Loops should not be infinite
Bug 阻斷
循環不應該是無限的