sonarQube常見問題及分析

阻斷
一、Close this"FileInputStream" in a "finally" clause.
在finally中關閉FileInputStream,這個最爲常見,主要是關閉方式不對,finally代碼塊中,應該要對每一個stream進行單獨關閉,而不能統一寫在一個try-catch代碼中,jdk 7 能夠考慮try-resources方式關閉,代碼相對優雅。

另外數據庫操做的statement和resultRs沒有關閉的狀況也很是多。這個也是要重點留意的地方。

二、A"NullPointerException" could be thrown; "tom" is nullablehere
空指針,極爲討厭的問題,主要是編碼經驗缺乏的體現。通常的高手在編碼過程當中,就會第一時間考慮到這類狀況,並作相應的處理。解決方式無它,先判斷或者先實例化,再訪問裏面的屬性或者成員。


嚴重
一、Define and throw a dedicated exception instead of using a generic one
定義並拋出一個專用的異常來代替一個通用的異常。

二、Removethis hard-coded password
移除代碼裏硬編碼的密碼信息。會有少量的誤判的狀況,通常是變量包含:PWD或者password,因此若是真的不是硬編碼,能夠考慮更換變量名稱,好比PWD改PW等等。

三、Eitherlog or rethrow this exception
catch異常以後,使用log方式或者throw異常的方式解決。若是業務上真的沒有throw或者記錄日誌的話,可使用log.debug的方式填充來解決問題。

四、Makethis IP "127.0.0.1" address configurable
將IP弄到配置文件中,不要硬編碼到代碼裏。我的以爲改動稍大!

五、Make this"public static JSAPI" field final
若是你將這個變量設置爲public訪問方式,同時又是靜態Static方式,就要考慮將它設置爲final了,由於這個是共享變量,其它類能夠隨時隨地將它設置爲別的值。因此若是是隻是當前類使用,能夠考慮將公開訪問方式改成私有。

六、Makethe enclosing method "static" or remove this set
見代碼:
public class MyClass {
private static int count = 0;
public void doSomething() {
//...
count++; // Noncompliant
}
}
不要使用非靜態方法去更新靜態字段,這樣很難得到正確的結果,若是有多個類實例和/或多個線程,則很容易致使錯誤。理想狀況下,靜態字段僅從同步靜態方法中更新。

七、Override"equals(Object obj)" to comply with the contract of the"compareTo(T o)" method
若是重寫了compareTo方法,同時也應重寫equals方法。

八、Make"body" transient or serializable.
public class Address {
//...
}

public class Person implements Serializable {
private static final long serialVersionUID = 1905122041950251207L;

private String name;
private Address address; // Noncompliant; Address isn't serializable
}


若是person已經序列化,其成員變量Address也進行序列化。否則轉化時會有問題。

9 Floating point numbers should not be tested for equality
浮點類型的數字,不要經過==或者!=方式其它類型比較,由於浮點是不精確的,因此在比較時,會進行類型升級升級原則以下:
· 若是運算符任意一方的類型爲double,則另外一方會轉換爲double
· 不然,若是運算符任意一方的類型爲float,則另外一方會轉換爲float
· 不然,若是運算符任意一方的類型爲long,則另外一方會轉換爲long
· 不然,兩邊都會轉換爲int

如下的方式獲得的結果都是false。
float myNumber = 3.146;
if ( myNumber == 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be false

if ( myNumber != 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be true


if (myNumber < 4 || myNumber > 4) { // Noncompliant; indirect

float zeroFloat = 0.0f;
if (zeroFloat == 0) { // Noncompliant. Computations may end up with a value close but not equal to zero.
}

因此,要比較浮點數是否相等,須要作的事情是:

排除NaN和無窮
在精度範圍內進行比較
正確的例子:
public boolean isEqual(double a, double b) {
if (Double.isNaN(a) || Double.isNaN(b) || Double.isInfinite(a) || Double.isInfinite(b)) {
return false;
}
return (a - b) < 0.001d;
}

十、Thiscall to "contains()" may be a performance hot spot if the collectionis large.
若是collection的記錄數很是大的話,它的contains方法的時間複雜度是很高的。因此開發過程當中要注意這一點。下面的是列表:
· ArrayList
contains
remove
· LinkedList
get
contains
· ConcurrentLinkedQueue
size
contains
· ConcurrentLinkedDeque
size
contains
· CopyOnWriteArrayList
add
contains
remove
· CopyOnWriteArraySet
add
contains
remove數據庫

相關文章
相關標籤/搜索