1. 程式人生 > >Sonar 常用代碼規則整理

Sonar 常用代碼規則整理

cycle 堆棧 方法參數 gate program @override 要求 provide rar

摘要:公司部署了一套sonar,經過一段時間運行,發現有一些問題出現頻率很高,因此有必要將這些問題進行整理總結和分析,避免再次出現類似問題。

作者原創技術文章,轉載請註明出處
id: 83 name: A method/constructor shouldnt explicitly throw java.lang.Exception type: CODE SMELL severity: MAJOR Comment: It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception. definition: 目前還不清楚可以從方法中拋出哪些異常。 可能難以記錄和了解模糊界面。 advice: 建議使用從RuntimeException派生的類或checked的異常。
id: 144 name: Avoid really long methods. type: CODE SMELL severity: MAJOR Comment: Violations of this rule usually indicate that the method is doing too much. Try to reduce the method size by creating helper methods and removing any copy/pasted code. definition: 違反此規則通常表明該方法做得太多。 嘗試通過創建幫助方法並刪除任何復制/粘貼代碼來減少方法大小。 advice: 建議方法代碼行數不超過75行
id: 1032 name: Redundant nullcheck of tbOfflinePay, which is known to be non-null in com.ctrip.market.web.controller.OrderController.getOrderPrintDetail(String, Integer, Long, String, String, String) type: CODE SMELL severity: MAJOR Comment: This method contains a redundant check of a known non-null value against the constant null. definition: 此方法包含對常量null的已知非空值的冗余檢查。 advice: 建議:先檢查是否為空再進行相關操作
id: 1097 name: Write to static field com.ctrip.market.materialfile.utils.SpringContextHolder.applicationContext from instance method com.ctrip.market.materialfile.utils.SpringContextHolder.destroy() type: CODE SMELL severity: CRITICAL Comment: This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice. definition: 此實例方法寫入靜態字段。如果多個實例被操縱,這是很難獲得正確的。這通常是壞的做法。 advice: 不要通過實例方法給靜態變量賦值
id: 1217 name: input must be non-null but is marked as nullable type: CODE SMELL severity: MAJOR Comment: This parameter is always used in a way that requires it to be non-null, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong. definition: 該參數始終以使其不為空的方式使用,但是將該參數顯式註釋為Nullable。 所以,參數或註釋是錯誤的。 advice: 參數值在任何情況下都不能為空,但是有明確的註釋它可以為空。
id: 1624 name: Assign this magic number 3 to a well-named constant, and use the constant instead. type: CODE SMELL severity: MAJOR Comment: "A magic number is a number that comes out of nowhere, and is directly used in a statement. Magic numbers are often used, for instance to limit the number of iterations of a loops, to test the value of a property, etc.

Using magic numbers may seem obvious and straightforward when you‘re writing a piece of code, but they are much less obvious and straightforward at debugging time.

That is why magic numbers must be demystified by first being assigned to clearly named variables before being used.

-1, 0 and 1 are not considered magic numbers." definition: "一個魔術數字是一個從無處出現的數字,直接用在一個語句中。 經常使用魔數,例如限制循環的叠代次數,以測試屬性的值等。
當您編寫一段代碼時,使用魔術數字可能看起來顯而易見,但在調試時間上它們不那麽明顯和直截了當。
這就是為什麽魔術數字必須被神秘化,首先被分配給明確命名的變量才能使用。
-1,0和1不被視為魔術數字。" advice: "不合規:
public static void doSomething() {
for(int i = 0; i < 4; i++){ // Noncompliant, 4 is a magic number
...
}
}
合規:
public static final int NUMBER_OF_CYCLES = 4;
public static void doSomething() {
for(int i = 0; i < NUMBER_OF_CYCLES ; i++){
...
}
}
例外:
這條規則忽略 hashCode 方法。"
id: 1645 name: This method has 158 lines, which is greater than the 100 lines authorized. Split it into smaller methods. type: CODE SMELL severity: MAJOR Comment: A method that grows too large tends to aggregate too many responsibilities. Such method inevitably become harder to understand and therefore harder to maintain. definition: 增長太大的方法往往會累積太多的責任。 這種方法不可避免地變得難以理解,因此更難維護。 advice: 較小的方法不但會更容易理解,也可能更容易測試。
id: 1701 name: Remove this empty statement. type: BUG severity: MINOR Comment: "Empty statements, i.e. ;, are usually introduced by mistake, for example because:

It was meant to be replaced by an actual statement, but this was forgotten.
There was a typo which lead the semicolon to be doubled, i.e. ;;." definition: "空的聲明,即.;,通常是錯誤的引入,例如:
這意味著被一個實際的陳述所取代,但這被遺忘了。
有一個拼寫錯誤,導致分號增加一倍,即. ;;。" advice: "不合規:
void doSomething() {
; // Noncompliant - was used as a kind of TODO marker
}

void doSomethingElse() {
System.out.println(""Hello, world!"");; // Noncompliant - double ;
...
for (int i = 0; i < 3; System.out.println(i), i++); // Noncompliant - Rarely, they are used on purpose as the body of a loop. It is a bad practice to have side-effects outside of the loop body
...
}
合規:
void doSomething() {}

void doSomethingElse() {
System.out.println(""Hello, world!"");
...
for (int i = 0; i < 3; i++){
System.out.println(i);
}
...
}"
id: 1722 name: Reduce the number of conditional operators (4) used in the expression (maximum allowed 3). type: CODE SMELL severity: CRITICAL Comment: The complexity of an expression is defined by the number of &&, || and condition ? ifTrue : ifFalse operators it contains. A single expression‘s complexity should not become too high to keep the code readable. definition: 表達式的復雜性由&&,||的數量定義 和它所包含的條件判斷? ifTrue:ifFalse等操作符所決定。 單個表達式的復雜度不應該變得太高,以致不能保持代碼的可讀性。 advice: "不合規代碼範例:

默認閾值為3的情況:

if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }
合規範例:

if ( (myFirstCondition() || mySecondCondition()) && myLastCondition()) { ... }"
id: 1728 name: This method has 122 lines, which is greater than the 100 lines authorized. Split it into smaller methods. type: CODE SMELL severity: MAJOR Comment: A method that grows too large tends to aggregate too many responsibilities. Such method inevitably become harder to understand and therefore harder to maintain. Above a specific threshold, it is strongly advised to refactor into smaller methods which focus on well-defined tasks. Those smaller methods will not only be easier to understand, but also probably easier to test. definition: 方法增長太大往往會累積太多的責任/幹系。 這種方法不可避免地變得難以理解,更難維護。 advice: 建議方法中最大行數:75
id: 1738 name: The Cyclomatic Complexity of this method "remarketingDataHandler" is 15 which is greater than 10 authorized. type: CODE SMELL severity: CRITICAL Comment: "The cyclomatic complexity of methods should not exceed a defined threshold.

Complex code can perform poorly and will in any case be difficult to understand and therefore to maintain." definition: 方法的循環復雜度不應超過定義的閾值。復雜的代碼表現較差,在任何情況下都難以理解,需要維護。 advice: 復雜度建議為10
id: 1759 name: Add a default case to this switch. type: CODE SMELL severity: MAJOR Comment: The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken. Even when the switch covers all current values of an enum, a default case should still be used because there is no guarantee that the enum won‘t be extended. definition: switch語句應該以default結束,這是一種defensive programming思想 advice: "不合規:
switch (param) { //missing default clause
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}

switch (param) {
default: // default clause should be the last one
error();
break;
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}
合規:
switch (param) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
default:
error();
break;
}"
id: 1809 name: Remove this call from a constructor to the overridable "setFormat" method. type: CODE SMELL severity: CRITICAL Comment: Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method. definition: 從構造函數調用一個可覆蓋的方法,可能導致在實例化覆蓋該方法的子類時出現故障或奇怪的行為。 advice: "不合規:

public class Parent {

public Parent () {
doSomething(); // Noncompliant
}

public void doSomething () { // not final; can be overridden
...
}
}

public class Child extends Parent {

private String foo;

public Child(String foo) {
super(); // leads to call doSomething() in Parent constructor which triggers a NullPointerException as foo has not yet been initialized
this.foo = foo;
}

public void doSomething () {
System.out.println(this.foo.length());
}

}"
id: 1819 name: Throw some other exception here, such as "IllegalArgumentException". type: CODE SMELL severity: MAJOR Comment: A NullPointerException should indicate that a null value was unexpectedly encountered. Good programming practice dictates that code is structured to avoid NPE‘s. definition: 良好的編程實踐規定代碼的結構是避免空值異常的。 advice: "不合規:
public void doSomething (String aString) throws NullPointerException {
throw new NullPointerException();
}
合規:
public void doSomething (@NotNull String aString) {
}"
id: 1826 name: Change this comparison to use the equals method. type: BUG severity: MAJOR Comment: Using the equality (==) and inequality (!=) operators to compare two objects does not check to see if they have the same values. Rather it checks to see if both object references point to exactly the same object in memory. The vast majority of the time, this is not what you want to do. Use the .equals() method to compare the values of two objects or to compare a string object to a string literal. definition: 使用等於(==)和不等式(!=)運算符比較兩個對象不會檢查它們是否具有相同的值。 相反,它會檢查兩個對象引用是否指向內存中完全相同的對象。 絕大多數時間,這不是你想做的事情。 使用.equals()方法來比較兩個對象的值,或比較字符串對象與字符串文字。 advice: "不合規:
String str1 = ""blue"";
String str2 = ""blue"";
String str3 = str1;

if (str1 == str2)
{
System.out.println(""they‘re both ‘blue‘""); // this doesn‘t print because the objects are different
}

if (str1 == ""blue"")
{
System.out.println(""they‘re both ‘blue‘""); // this doesn‘t print because the objects are different
}

if (str1 == str3)
{
System.out.println(""they‘re the same object""); // this prints
}
合規:
String str1 = ""blue"";
String str2 = ""blue"";
String str3 = str1;

if (str1.equals(str2))
{
System.out.println(""they‘re both ‘blue‘""); // this prints
}

if (str1.equals(""blue""))
{
System.out.println(""they‘re both ‘blue‘""); // this prints
}

if (str1 == str3)
{
System.out.println(""they‘re the same object""); // this still prints, but it‘s probably not what you meant to do
}"
id: 1837 name: Make this class "final" or add a public constructor. type: CODE SMELL severity: MAJOR Comment: Classes with only private constructors should be marked final to prevent any mistaken extension attempts. definition: 只有私有構造函數的類應該被標記為final advice: "不合規:
public class PrivateConstructorClass { // Noncompliant
private PrivateConstructorClass() {
// ...
}

public static int magic(){
return 42;
}
}
合規:
public final class PrivateConstructorClass { // Compliant
private PrivateConstructorClass() {
// ...
}

public static int magic(){
return 42;
}
}"
id: 1846 name: Rename this local variable name to match the regular expression ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MINOR Comment: Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all local variable and function parameter names match a provided regular expression. definition: 共享一些命名約定是使團隊有可能高效協作的關鍵。 此規則允許檢查所有本地變量和函數參數名稱是否與提供的正則表達式匹配。 advice: "不合規:
With the default regular expression ^[a-z][a-zA-Z0-9]*$:

public void doSomething(int my_param) {
int LOCAL;
...
}
合規:

public void doSomething(int myParam) {
int local;
...
}
例外:

循環計數可以忽略這條規則

for (int i = 0; i < limit; i++) { // Compliant
// ...
}"
id: 1856 name: Rename this field "TopLevel" to match the regular expression ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MINOR Comment: Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all local variable and function parameter names match a provided regular expression. definition: 共享一些命名約定是使團隊有可能高效協作的關鍵。 此規則允許檢查所有本地變量和函數參數名稱是否與提供的正則表達式匹配。 advice: "不合規:
With the default regular expression ^[a-z][a-zA-Z0-9]*$:

public void doSomething(int my_param) {
int LOCAL;
...
}
合規:
public void doSomething(int myParam) {
int local;
...
}
例外:

循環計數被該規則忽略

for (int i = 0; i < limit; i++) { // Compliant
// ...
}
"
id: 1861 name: Cyclomatic Complexity is 11 (max allowed is 10). type: CODE SMELL severity: MAJOR Comment: Checks cyclomatic complexity of methods against a specified limit. The complexity is measured by the number of if, while, do, for, ?:, catch, switch, case statements, and operators && and || (plus one) in the body of a constructor, method, static initializer, or instance initializer. It is a measure of the minimum number of possible paths through the source and therefore the number of required tests. Generally 1-4 is considered good, 5-7 ok, 8-10 consider re-factoring, and 11+ re-factor now definition: 檢查針對特定限制的方法的循環復雜性。 復雜度由if,while,do,for,...,catch,switch,case語句和運算符&&和||的數量來衡量。 (加一個)在構造函數,方法,靜態初始化程序或實例初始化程序的正文中。 它是通過源代碼的可能路徑的最小數量的度量,因此是所需測試的數量。 一般來說,1-4被認為是好的,5-7可以,8-10考慮重新分解,11+的建議馬上重構 advice: 大於10建議重構
id: 1884 name: Rename this class name to match the regular expression ‘^[A-Z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MINOR Comment: Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all class names match a provided regular expression. definition: 共享一些命名約定是使團隊有可能高效協作的關鍵。 此規則允許檢查所有類名稱是否與提供的正則表達式相匹配。 advice: "不合規:
默認提供正則表達式 ^[A-Z][a-zA-Z0-9]*$:
class my_class {...}

合規:
class MyClass {...}"
id: 1885 name: Rename this method name to match the regular expression ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MAJOR Comment: Shared naming conventions allow teams to collaborate efficiently. This rule checks that all method names match a provided regular expression. definition: 此規則檢查所有方法名稱是否與提供的正則表達式匹配。 advice: "不合規:
public int DoSomething(){...}
合規:
public int doSomething(){...}
例外:(重寫的方法)
@Override
public int Do_Something(){...}"
id: 1921 name: Remove this unused "MKT_Clean_GroupID" private field. type: CODE SMELL severity: MAJOR Comment: If a private field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for. definition: 如果一個私有變量被聲明但未被使用,那麽它是死代碼應該被刪除。 這樣做會提高可維護性,因為開發人員並不想知道這個變量用來作甚。 advice: "不合規:
public class MyClass {
private int foo = 42;
public int compute(int a) {
return a * 42;
}
}
合規:
public class MyClass {
public int compute(int a) {
return a * 42;
}
}"
id: 1926 name: Name XXXXXX must match pattern ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MAJOR Comment: Checks that parameter names conform to the specified format definition: 檢查參數名稱是否符合指定格式 advice: 建議按照命名規範
id: 1929 name: Remove this unused method parameter "payinfo". type: CODE SMELL severity: MAJOR Comment: Unused parameters are misleading. Whatever the value passed to such parameters is, the behavior will be the same. definition: 未使用的參數會造成誤導。因為無論傳遞給這些參數的值是什麽,函數行為並不會發生變化。 advice: "不合規:
void doSomething(int a, int b) { // ""b"" is unused
compute(a);
}
合規:
void doSomething(int a) {
compute(a);
}"
id: 1944 name: Remove this unused "empsEntity" local variable. type: CODE SMELL severity: MINOR Comment: "If a local variable is declared but not used, it is dead code and should be removed. Doing so will improve maintainability because developers will not wonder what the variable is used for.
" definition: 如果一個局部變量被聲明但未被使用,那麽它是死代碼應該被刪除。 這樣做會提高可維護性,因為開發人員並不想知道這個變量用來作甚。 advice: "不合規:
public int numberOfMinutes(int hours) {
int seconds = 0; // seconds is never used
return hours * 60;
}
合規:
public int numberOfMinutes(int hours) {
return hours * 60;
}"
id: 1964 name: Remove this unused private "setUpVidList" method. type: CODE SMELL severity: MINOR Comment: private methods that are never executed are dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced. definition: 從未執行的私有方法是死碼:不必要的,應該被刪除的代碼。清理死碼會減少維護的代碼庫的大小,從而更容易理解程序並防止引入錯誤。 advice: "不合規:
public class Foo implements Serializable
{
private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class.
public static void doSomething(){
Foo foo = new Foo();
...
}
private void unusedPrivateMethod(){...}
private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism
private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism
}
合規:
public class Foo implements Serializable
{
private Foo(){} //Compliant, private empty constructor intentionally used to prevent any direct instantiation of a class.
public static void doSomething(){
Foo foo = new Foo();
...
}

private void writeObject(ObjectOutputStream s){...} //Compliant, relates to the java serialization mechanism

private void readObject(ObjectInputStream in){...} //Compliant, relates to the java serialization mechanism
}"
id: 1965 name: Remove this unused import ‘com.ctrip.market.dmp.remarketing.business.Models.DashboardMetrics‘. type: CODE SMELL severity: INFO Comment: The imports part of a file should be handled by the Integrated Development Environment (IDE), not manually by the developer. definition: 無用的imports應該刪除 advice: 文件的導入部分應由集成開發環境(IDE)處理,而不是由開發人員手動處理。
id: 1986 name: Unused import - XXXXXX type: CODE SMELL severity: INFO Comment: The imports part of a file should be handled by the Integrated Development Environment (IDE), not manually by the developer. definition: 無用的imports應該刪除 advice: 文件的導入部分應由集成開發環境(IDE)處理,而不是由開發人員手動處理。
id: 1995 name: Name XXX must match pattern ‘^[a-z]+(\.[a-zA-Z_][a-zA-Z0-9_]*)*$‘. type: CODE SMELL severity: MAJOR Comment: Checks that package names conform to the specified format. The default value of format has been chosen to match the requirements in the Java Language specification and the Sun coding conventions. However both underscores and uppercase letters are rather uncommon, so most configurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$ to format definition: "
檢查包名是否符合指定的格式。 已經選擇了格式的默認值,以匹配Java語言規範和Sun編碼約定中的要求。" advice: 建議大多數配置應該可以分配值^ [a-z] +(\。[a-z] [a-z0-9] *)* $來格式化
id: 2001 name: Name XXX must match pattern ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: MAJOR Comment: Checks that parameter names conform to the specified format definition: 檢查參數名稱是否符合指定格式 advice: 建議按照命名規範
id: 2003 name: Either remove or fill this block of code. type: CODE SMELL severity: MAJOR Comment: Most of the time a block of code is empty when a piece of code is really missing. So such empty block must be either filled or removed. definition: 當一段代碼真的丟失時,大多數時候代碼塊是空的。 所以這樣的空塊必須被填充或刪除。 advice: "不合規:
for (int i = 0; i < 42; i++){} // Empty on purpose or missing piece of code ?"
id: 2014 name: Use a logger to log this exception. type: ISSUE severity: MINOR Comment: "Throwable.printStackTrace(...) prints a Throwable and its stack trace to some stream. By default that stream System.Err, which could inadvertently expose sensitive information.

Loggers should be used instead to print Throwables, as they have many advantages:

Users are able to easily retrieve the logs.
The format of log messages is uniform and allow users to browse the logs easily.
This rule raises an issue when printStackTrace is used without arguments, i.e. when the stack trace is printed to the default stream." definition: "Throwable.printStackTrace(...)將Throwable及其堆棧跟蹤打印到某些流。 默認情況下,流System.Err可能會無意中暴露敏感信息。
應該使用日誌消息來代替打印Throwables,因為它們有很多優點:
用戶能夠輕松地檢索日誌。日誌消息的格式是統一的,用戶可以輕松瀏覽日誌。" advice: "不合規:
try {
/* ... */
} catch(Exception e) {
e.printStackTrace();
}
合規:
try {
/* ... */
} catch(Exception e) {
LOGGER.log(""context"", e);
}"
id: 2018 name: Rename this package name to match the regular expression ‘^[a-z]+(\\.[a-z][a-z0-9]*)*$‘. type: CODE SMELL severity: MAJOR Comment: Shared coding conventions allow teams to collaborate efficiently. This rule checks that all package names match a provided regular expression. definition: 此規則檢查所有包名稱是否與提供的正則表達式匹配。 advice: "不合規:
package org.exAmple; //不符合
合規:
package org.example;"
id: 2027 name: Rename this local variable name to match the regular expression ‘^[a-z][a-zA-Z0-9]*$‘. type: CODE SMELL severity: INFO Comment: Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate. This rule allows to check that all local variable and function parameter names match a provided regular expression. definition: 局部變量和方法參數名稱應符合命名約定 advice: "不合規:
public void doSomething(int my_param) {
int LOCAL;
...
}
合規:
public void doSomething(int myParam) {
int local;
...
}
例外:
循環計數器被該規則忽略。
for (int i = 0; i < limit; i++) { // Compliant
// ...
}"

附錄:參考

Java代碼規範小結(一):http://www.jianshu.com/p/b50f01eeba4d

FindBugs Report安全代碼檢查工具問題解析:http://blog.csdn.net/wwbmyos/article/details/50549650

FindBugs規則整理(轉載):http://blog.csdn.net/hufang_lele/article/details/47090215

作者原創技術文章,轉載請註明出處

Sonar 常用代碼規則整理