Sonar 規則及相關提示處理

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 阻斷
循環不應該是無限的

 

 

 


漏洞類型:


1、"@RequestMapping" methods should be "public"
漏洞 阻斷
標註了RequestMapping是controller是處理web請求。既使方法修飾爲private,同樣也能被外部調用,因爲spring通過反射調用方法,沒有檢查方法可視度,
2、"enum" fields should not be publicly mutable
漏洞 次要
枚舉類域不應該是public,也不應該進行set
3、"File.createTempFile" should not be used to create a directory
漏洞 嚴重
File.createTempFile不應該被用來創建目錄
4、"HttpServletRequest.getRequestedSessionId()" should not be used
漏洞 嚴重
HttpServletRequest.getRequestedSessionId()返回客戶端瀏覽器會話id不要用,用HttpServletRequest.getSession().getId()
5、"javax.crypto.NullCipher" should not be used for anything other than testing
漏洞 阻斷
NullCipher類提供了一種“身份密碼”,不會以任何方式轉換或加密明文。 因此,密文與明文相同。 所以這個類應該用於測試,從不在生產代碼中。
6、"public static" fields should be constant
漏洞 次要
public static 域應該 final
7、Class variable fields should not have public accessibility
漏洞 次要
類變量域應該是private,通過set,get進行操作
8、Classes should not be loaded dynamically
漏洞 嚴重
不應該動態加載類,動態加載的類可能包含由靜態類初始化程序執行的惡意代碼.
Class clazz = Class.forName(className); // Noncompliant
9、Cookies should be "secure"
漏洞 次要
Cookie c = new Cookie(SECRET, secret); // Noncompliant; cookie is not secure
response.addCookie(c);
正:
Cookie c = new Cookie(SECRET, secret);
c.setSecure(true);
response.addCookie(c);
10、Credentials should not be hard-coded
漏洞 阻斷
憑證不應該硬編碼
11、Cryptographic RSA algorithms should always incorporate OAEP (Optimal Asymmetric Encryption Padding)
漏洞 嚴重
加密RSA算法應始終包含OAEP(最優非對稱加密填充)
12、Default EJB interceptors should be declared in "ejb-jar.xml"
漏洞 阻斷
默認EJB攔截器應在“ejb-jar.xml”中聲明
13、Defined filters should be used
漏洞 嚴重
web.xml文件中定義的每個過濾器都應該在<filter-mapping>元素中使用。 否則不會調用此類過濾器。
14、Exceptions should not be thrown from servlet methods
漏洞 次要
不應該從servlet方法拋出異常
15、HTTP referers should not be relied on
漏洞 嚴重
不應依賴於http,將這些參數值中止後可能是安全的,但絕不應根據其內容作出決定。
如:
String referer = request.getHeader("referer"); // Noncompliant
if(isTrustedReferer(referer)){
//..
}
16、IP addresses should not be hardcoded
漏洞 次要
ip 地址不應該硬編碼
17、Member variable visibility should be specified
漏洞 次要
應指定成員變量的可見性
18、Members of Spring components should be injected
漏洞 嚴重
spring組件的成員應注入,單例注入非靜態成員共享會產生風險
19、Mutable fields should not be "public static"
漏洞 次要
多變在域不應爲 public static
20、Neither DES (Data Encryption Standard) nor DESede (3DES) should be used
漏洞 阻斷
不應使用DES(數據加密標準)和DESEDE(3DES)
21、Only standard cryptographic algorithms should be used
漏洞 嚴重
標準的加密算法如 SHA-256, SHA-384, SHA-512等,非標準算法是危險的,可能被功能者攻破算法
22、Pseudorandom number generators (PRNGs) should not be used in secure contexts
漏洞 嚴重
僞隨機數生成器(PRNG)不應在安全上下文中使用
23、Return values should not be ignored when they contain the operation status code
漏洞 次要
當函數調用的返回值包含操作狀態代碼時,應該測試此值以確保操作成功完成。
24、Security constraints should be definedin
漏洞 阻斷
應定義安全約束,當web.xml文件沒有<security-constraint>元素時,此規則引發了一個問題
25、SHA-1 and Message-Digest hash algorithms should not be used
漏洞 嚴重
不應該使用SHA-1和消息摘要散列算法,已證實不再安全
26、SQL binding mechanisms should be used
漏洞 阻斷
應該使用SQL綁定機制
27、Struts validation forms should have unique names
漏洞 阻斷
struts驗證表單應有唯一名稱
28、Throwable.printStackTrace(...) should not be called
漏洞 次要
Throwable.printStackTrace(...)會打印異常信息,但會暴露敏感信息
29、Untrusted data should not be stored in sessions
漏洞 主要
不受信任的數據不應存儲在會話中。
Web會話中的數據被認爲在“信任邊界”內。 也就是說,它被認爲是值得信賴的。 但存儲未經身份驗證的用戶未經驗證的數據違反信任邊界,並可能導致該數據被不當使用。
30、Values passed to LDAP queries should be sanitized
漏洞 嚴重
傳遞到LDAP查詢的值應該被清理
31、Values passed to OS commands should be sanitized
漏洞 嚴重
傳遞給OS命令的值應該被清理
32、Web applications should not have a "main" method
漏洞 嚴重
web 應用中不應有一個main方法

 

 


壞味道:


1、"==" and "!=" should not be used when "equals" is overridden
壞味道 次要
當類重寫equals方法後,不應該再用"=="與"!="進行對象比較
2、"@Deprecated" code should not be used
壞味道 次要
棄用方代碼不應再用,棄用代碼意味首將會移除,應該使用替代代碼
3、"@Override" should be used on overriding and implementing methods
壞味道 主要
重寫的和實現在方法要加Override標註
4、"action" mappings should not have too many "forward" entries
壞味道 次要
默認 4
action不要有太多的forward
5、"Arrays.stream" should be used for primitive arrays
壞味道 主要
Arrays.stream用於原始流類型(IntStream, LongStream, DoubleStream)會有更好的性能
6、"catch" clauses should do more than rethrow
壞味道 次要
只是重新拋出捕獲的異常和完全放棄異常捕獲效果一樣,但會給維護者帶來疑惑
7、"clone" should not be overridden
壞味道 阻斷
不應重寫clone方法
8、"Cloneables" should implement "clone"
壞味道 嚴重
Cloneables類應該實現clone方法
9、"collect" should be used with "Streams" instead of "list::add"
壞味道 次要
雖然您可以使用forEach(list :: add)或使用Stream收集,但是收集是更好的選擇,因爲它自動線程安全並且可並行
10、"Collections.EMPTY_LIST", "EMPTY_MAP", and "EMPTY_SET" should not be used
壞味道 次要
11、"DateUtils.truncate" from Apache Commons Lang library should not be used
壞味道 主要
使用Java 8中引入的Instant類來截斷日期可能會比Commons Lang的DateUtils類快得多。
12、"deleteOnExit" should not be used
壞味道 主要
不推薦使用File.deleteOnExit()
13、"entrySet()" should be iterated when both the key and value are needed
壞味道 主要
當循環中只需要一個map的鍵時,迭代keySet就是有意義的。 但是,當需要鍵和值兩者時,迭代entrySet更有效,這將允許訪問鍵和值
14、"equals(Object obj)" should be overridden along with the "compareTo(T obj)" method
壞味道 次要
“equals(Object obj)”應該與“compareTo(T obj)”方法一起被重寫
15、"Exception" should not be caught when not required by called methods
壞味道 次要
如果被調方法沒有拋出“Exception”時不要捕獲"Exception",應捕後被調方法拋出的異常
16、"final" classes should not have "protected" members
壞味道 次要
最終類意味首不可繼承所以不要有受保存成員,這樣沒有意義
17、"finalize" should not set fields to "null"
壞味道 次要
finalize不應設置域空,對垃圾收集是沒必要的,還可能爲垃圾收集帶來額處開消
18、"for" loop increment clauses should modify the loops' counters
壞味道 嚴重
loop循環應該增加遞增序號變量
19、"for" loop stop conditions should be invariant
壞味道 主要
循環停止條件應爲不變
20、"indexOf" checks should not be for positive numbers
壞味道 嚴重
檢查indexOf返回不應使用正數
21、"indexOf" checks should use a start position
壞味道 次要
如果您需要查看一個子字符串是否位於字符串中某個特定點之外,則可以測試該子字符串與該目標點的indexOf,也可以使用該起始點參數的indexOf版本。 後者可以更清楚,因爲結果是針對-1測試的,這是一個容易識別的“未找到”指標
22、"java.lang.Error" should not be extended
壞味道 主要
java.lang.Error及其子類表示異常情況,例如OutOfMemoryError,它只能由Java虛擬機進行處理。
23、"java.nio.Files#delete" should be preferred
壞味道 主要
Files.delete(path)道選
24、"java.time" classes should be used for dates and times
壞味道 主要
Date 和 Calendar類非線程同步,推薦使用LocalDate
25、"Lock" objects should not be "synchronized"
壞味道 主要
“鎖定”對象不應“同步”
java.util.concurrent.locks.Lock提供比同步塊更強大和靈活的鎖定操作,應該使用tryLock()和unlock()鎖定和解鎖這些對象
26、"main" should not "throw" anything
壞味道 阻斷
main方法不應該拋出異常
27、"NullPointerException" should not be caught
壞味道 主要
空指針不應捕獲處理,應該避免NullPointerException,而不是被捕獲
28、"NullPointerException" should not be explicitly thrown
壞味道 主要
“NullPointerException”不應該被顯式拋出
29、"Object.finalize()" should remain protected (versus public) when overriding
壞味道 嚴重
重寫finalizey方法應爲protected
30、"Object.wait(...)" and "Condition.await(...)" should be called inside a "while" loop
壞味道 嚴重
“Object.wait(...)”和“Condition.await(...)”應該在“while”循環內調用
31、"Object.wait(...)" should never be called on objects that implement "java.util.concurrent.locks.Condition"
壞味道 主要
不應該在實現“java.util.concurrent.locks.Condition”的對象上調用“Object.wait(...)”
32、"Optional" should not be used for parameters
壞味道 主要
Optional不要被用作參數
33、"Preconditions" and logging arguments should not require evaluation
壞味道 主要
將連接的字符串傳遞到日誌記錄方法也可能導致不必要的性能消耗,因爲每次調用該方法時將執行級聯,無論日誌級別是否足夠低以顯示消息
34、"private" methods called only by inner classes should be moved to those classes
壞味道 次要
只被內部類調用的方法,應該在內部類內部
35、"private" methods that don't access instance data should be "static"
壞味道 次要
不訪問實例數據的“私有”方法應該是“靜態”
36、"readObject" should not be "synchronized"
壞味道 主要
“readObject”不應該被“同步”
37、"readResolve" methods should be inheritable
壞味道 嚴重
“readResolve”方法應該是可繼承的
38、"ResultSet.isLast()" should not be used
壞味道 主要
ResultSet.isLast()不應用
39、"Serializable" classes should have a version id
壞味道 嚴重
“Serializable”類應該有一個版本號
40、"Serializable" inner classes of "Serializable" classes should be static
壞味道 次要
實現序列化的內部類應該是靜態的
41、"static" members should be accessed statically
壞味道 主要
“靜態”成員應類訪問
42、"Stream.anyMatch()" should be preferred
壞味道 次要
“Stream.anyMatch()”應該是首選的
43、"switch case" clauses should not have too many lines of code
壞味道 主要
默認 5
“switch case”子句不應該有太多的代碼行
44、"switch" statements should end with "default" clauses
壞味道 嚴重
“switch”語句應以“default”子句結尾
45、"switch" statements should have at least 3 "case" clauses
壞味道 次要
“switch”語句應具有至少3個“case”子句,可以用if替代
46、"switch" statements should not contain non-case labels
壞味道 阻斷
switch語句不用包含非case標籤
47、"switch" statements should not have too many "case" clauses
壞味道 主要
默認 30
switch語句不應包含太多case語句
48、"Thread.sleep" should not be used in tests
壞味道 主要
“Thread.sleep”不應該在測試中使用
49、"ThreadLocal.withInitial" should be preferred
壞味道 次要
“ThreadLocal.withInitial”應該是首選
ThreadLocal<List<String>> myThreadLocal = ThreadLocal.withInitial(ArrayList::new);
50、"Threads" should not be used where "Runnables" are expected
壞味道 主要
Noncompliant Code Example
public static void main(String[] args) {
Thread r =new Thread() {
int p;
@Override
public void run() {
while(true)
System.out.println("a");
}
};
new Thread(r).start(); // Noncompliant
Compliant Solution


public static void main(String[] args) {
Runnable r =new Runnable() {
int p;
@Override
public void run() {
while(true)
System.out.println("a");
}
};
new Thread(r).start();
51、"throws" declarations should not be superfluous
壞味道 次要
“拋出”聲明不應該是多餘的
52、"toString()" should never be called on a String object
壞味道 次要
不應該在String對象上調用“toString()”
53、"URL.hashCode" and "URL.equals" should be avoided
壞味道 主要
應避免使用“URL.hashCode”和“URL.equals”
54、"writeObject" should not be the only "synchronized" code in a class
壞味道 主要
“writeObject”不應該是類中唯一的“同步”代碼
55、 @FunctionalInterface annotation should be used to flag Single Abstract Method interfaces
壞味道 嚴重
一個只有一個抽象方法的接口應加FunctionalInterface註釋
56、A "while" loop should be used instead of a "for" loop
壞味道 次要
當在for循環中僅定義條件表達式,並且缺少初始化和增量表達式時,應使用while循環來增加可讀性
57、A close curly brace should be located at the beginning of a line
壞味道 次要
共享編碼約定使得團隊有可能有效地進行協作。 這個規則使得強制要在行的開頭放置一個大括號。
58、A field should not duplicate the name of its containing class
壞味道 主要
字段不應該重複其包含的類的名稱
59、Abbreviation As Word In Name
壞味道 主要
檢查驗證標識符名稱中的縮寫(連續大寫字母)長度,還允許執行駱駝案例命名
60、Abstract Class Name
壞味道 主要
檢查抽象類名是否符合指定的格式
ignoreName
Controls whether to ignore checking the name. Realistically only useful if using the check to identify that match name and do not have the abstract modifier name. Default is false.
默認值
false
ignoreModifier
Controls whether to ignore checking for the abstract modifier on classes that match the name. Default is false.
默認值
false
format
Regular expression
默認值

61、Abstract class names should comply with a naming convention
壞味道 次要
抽象類名稱應符合命名約定

Regular expression used to check the abstract class names against.
默認值
^Abstract[A-Z][a-zA-Z0-9]*$
62、Abstract classes without fields should be converted to interfaces
壞味道 次要
沒有字段的抽象類應該轉換爲接口
63、Abstract methods should not be redundant
壞味道 次要
抽象方法不應該是多餘的
64、An abstract class should have both abstract and concrete methods
壞味道 次要
抽象類應該有抽象和具體的方法
65、An open curly brace should be located at the beginning of a line
壞味道 次要
開放的大括號應位於一行的開頭
66、An open curly brace should be located at the end of a line
壞味道 次要
開放的大括號應位於一行的末尾
67、Annotation arguments should appear in the order in which they were declared
壞味道 次要
註釋參數應按其聲明順序顯示
68、Annotation Location
壞味道 主要
註釋位置
allowSamelineSingleParameterlessAnnotation
To allow single parameterless annotation to be located on the same line as target element.
默認值
true
allowSamelineParameterizedAnnotation
To allow parameterized annotation to be located on the same line as target element.
默認值
false
allowSamelineMultipleAnnotations
To allow annotation to be located on the same line as target element.
默認值
false
tokens

tokens to check
默認值
CLASS_DEF,INTERFACE_DEF,ENUM_DEF,METHOD_DEF,CTOR_DEF,VARIABLE_DEF
69、Annotation repetitions should not be wrapped
壞味道 次要
註釋重複不應包裝
70、Annotation Use Style
壞味道 主要

trailingArrayComma
Defines the policy for trailing comma in arrays. Default is never.
closingParens

Defines the policy for ending parenthesis. Default is never.
elementStyle

Defines the annotation element styles. Default value is compact_no_array.
71、Anon Inner Length
壞味道 主要
檢查長匿名內部類。
max

maximum allowable number of lines. Default is 20.
72、Anonymous inner classes containing only one method should become lambdas
壞味道 主要
只有一個方法的匿名內部類應該變成lambdas
jdk8以下自動禁用
73、Array designators "[]" should be located after the type in method signatures
壞味道 次要
數組代號“[]”應位於方法簽名類型之後
74、Array designators "[]" should be on the type, not the variable
壞味道 次要
數組代號“[]”應位於類型之後而不是變量之後
75、Array Trailing Comma
壞味道 主要
檢查數組初始化是否包含逗號
76、Array Type Style
壞味道 次要
數組類型樣式
javaStyle

Controls whether to enforce Java style (true) or C style (false). Default is true.
77、Arrays should not be created for varargs parameters
壞味道 次要
不應爲varargs參數創建數組
78、Artifact ids should follow a naming convention
壞味道 次要
共享命名約定允許團隊有效協作。 當pom的artifactId與提供的正則表達式不匹配時,此規則引發了一個問題

regex

The regular expression the "artifactId" should match
默認值
[a-z][a-z-0-9]+
79、Assertions should be complete
壞味道 阻斷
斷言應該是完整的
80、Assignments should not be made from within sub-expressions
壞味道 主要
不應在子表達式中作出賦值操作當賦值變量沒有用到
81、At-clause Order
壞味道 主要
檢查從句順序
tagOrder

allows to specify the order by tags.
默認值
@author,@version,@param,@return,@throws,@exception,@see,@since,@serial,@serialField,@serialData,@deprecated
target

allows to specify targets to check at-clauses.
82、Avoid Escaped Unicode Characters
壞味道 主要
避免轉義的Unicode字符

allowIfAllCharactersEscaped
Allow if all characters in literal are escaped.
默認值
false
allowNonPrintableEscapes
Allow non-printable escapes.
默認值
false
allowByTailComment
Allow use escapes if trail comment is present.
默認值
false
allowEscapesForControlCharacters
Allow use escapes for non-printable(control) characters.
默認值
false
83、Avoid Inline Conditionals
壞味道 次要
避免內聯條件
84、Avoid Nested Blocks
壞味道 主要
避免嵌套塊
allowInSwitchCase

Allow nested blocks in case statements. Default is false.
85、Avoid Star Import
壞味道 次要
檢查發現使用*符號的導入語句
excludes

packages where star imports are allowed. Note that this property is not recursive, subpackages of excluded packages are not automatically excluded.
allowStaticMemberImports
whether to allow starred static member imports like <code>import static org.junit.Assert.*;</code>. Default is false.
默認值
false
allowClassImports
whether to allow starred class imports like <code>import java.util.*;</code>. Default is false.
默認值
false
86、Avoid Static Import
壞味道 次要
避免靜態導入
87、Boolean checks should not be inverted
壞味道 次要
布爾檢查不應該被反轉
Noncompliant Code Example


if ( !(a == 2)) { ...} // Noncompliant
boolean b = !(i < 10); // Noncompliant
Compliant Solution


if (a != 2) { ...}
boolean b = (i >= 10);
88、Boolean Expression Complexity
壞味道 主要
將嵌套布爾運算符(&&,||和^)限制爲指定的深度(默認= 3)。

max

the maximum allowed number of boolean operations in one expression. Default is 3.
默認值
3
tokens

tokens to check. Default is LAND,BAND,LOR,BOR,BXOR.
默認值
LAND,BAND,LOR,BOR,BXOR
89、Boolean expressions should not be gratuitous
壞味道 主要
如果boolean表達式的值是已定的,那麼boolean表達式是沒有必要的可以移除
90、Boolean literals should not be redundant
壞味道 次要
boolean不需再與true,false比較作爲boolean表達式
91、Branches should have sufficient coverage by tests
壞味道 主要
分支應有足夠的測試覆蓋

minimumBranchCoverageRatio
默認值
65
92、Case insensitive string comparisons should be made without intermediate upper or lower casing
壞味道 次要
使用toLowerCase()或toUpperCase()來使不區分大小寫的比較無效,因爲它需要創建臨時的中間String對象。
93、Catch Parameter Name
壞味道 主要
檢查catch參數名是否符合format屬性指定的格式

format

Specifies valid identifiers. Default is ^(e|t|ex|[a-z][a-z][a-zA-Z]+)$
默認值
^(e|t|ex|[a-z][a-z][a-zA-Z]+)$
94、Catches should be combined
壞味道 次要
由於Java 7可以一次捕獲多個異常。 因此,當多個catch塊具有相同的代碼時,它們應該被組合以便更好的可讀性,sonar.java.source低於7時,此規則將自動禁用
95、Checked exceptions should not be thrown
壞味道 主要
檢查的異常不應該被拋出,要處理
96、Child class fields should not shadow parent class fields
壞味道 阻斷
子類字段不應該private父類的非private字段
97、Class Data Abstraction Coupling
壞味道 主要
度量衡量給定類中其他類的實例化數。

max

the maximum threshold allowed. Default is 7.
excludedClasses
User-configured class names to ignore.
excludeClassesRegexps
User-configured regular expressions to ignore classes
excludedPackages
User-configured packages to ignore
98、Class Fan Out Complexity
壞味道 主要
類的依賴類數量

max

the maximum threshold allowed. Default is 20.
excludedClasses
User-configured class names to ignore
excludeClassesRegexps
User-configured regular expressions to ignore classes
excludedPackages
User-configured packages to ignore
99、Class names should comply with a naming convention
壞味道 次要
類名應符合命名約定

format

Regular expression used to check the class names against.
默認值
^[A-Z][a-zA-Z0-9]*$
100、Class names should not shadow interfaces or superclasses
壞味道 嚴重
類名稱不應該影響接口或超類(相同)
101、Class Type(Generic) Parameter Name
壞味道 主要
泛型參數名稱符合指定的格式

format

Regular expression
默認值
^[A-Z]$
102、Classes and enums with private members should have a constructor
壞味道 主要
有私有成員的類和枚舉應該有一個構造函數
103、Classes and methods that rely on the default system encoding should not be used
壞味道 次要
不應使用依賴於默認系統編碼的類和方法
104、Classes from "sun.*" packages should not be used
壞味道 主要
不得使用“sun.*”軟件包的類,sun類*或com.sun *包被視爲實現細節,不屬於Java API

Exclude

Comma separated list of Sun packages to be ignored by this rule. Example: com.sun.jna,sun.misc
105、Classes named like "Exception" should extend "Exception" or a subclass
壞味道 主要
名爲“異常”的類應該擴展“異常”或者一個子類
106、Classes should not access their own subclasses during initialization
壞味道 嚴重
類在初始化期間不應訪問自己的子類
107、Classes should not be coupled to too many other classes (Single Responsibility Principle)
壞味道 主要
類不應與太多其他類(單一責任原則)相耦合(依賴)

max

Maximum number of classes a single class is allowed to depend upon
默認值
20
108、Classes should not be empty
壞味道 次要
空類沒意義,作爲公共擴展點可以作爲接口
109、Classes should not be too complex
壞味道 嚴重 廢棄
類不應太複雜

max

Maximum complexity allowed.
默認值
200
110、Classes should not have too many "static" imports
壞味道 主要
靜態導入類允許您使用其公共靜態成員,而不必使用類名。 這可以很方便,但如果靜態導入太多的類,你的代碼可能會變得混亂,很難維護

threshold

The maximum number of static imports allowed
默認值
4
111、Classes should not have too many fields
壞味道 主要
類不應有太多字段
countNonpublicFields

Whether or not to include non-public fields in the count
默認值
true
maximumFieldThreshold
The maximum number of fields
默認值
20
112、Classes should not have too many methods
壞味道 主要
類不應該有太多方法

countNonpublicMethods
Whether or not to include non-public methods in the count.
默認值
true
maximumMethodThreshold
The maximum number of methods authorized in a class.
默認值
35
113、Classes that override "clone" should be "Cloneable" and call "super.clone()"
壞味道 次要
覆蓋“克隆”的類應該是“可克隆”,並調用“super.clone()”
114、Classes with only "static" methods should not be instantiated
壞味道 主要
只有“靜態”方法的類不應該被實例化
115、Classes without "public" constructors should be "final"
壞味道 次要
只有私有構造函數的類應該被標記爲final,以防止任何錯誤的擴展嘗試。
116、Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line
壞味道 次要
關閉大括號,下一個“else”,“catch”和“finally”關鍵字應位於同一行
117、Close curly brace and the next "else", "catch" and "finally" keywords should be on two different lines
壞味道 次要
關閉大括號和下一個“else”,“catch”和“finally”關鍵字應該在兩個不同的行
118、Cognitive Complexity of methods should not be too high
壞味道 嚴重
認知複雜度是衡量一種方法的控制流程難以理解的度量。 認知複雜性較高的方法難以維持。
Threshold

The maximum authorized complexity.
默認值
15
119、Collapsible "if" statements should be merged
壞味道 主要
可合併的“if”語句應該合併
120、Collection methods with O(n) performance should be used carefully
壞味道 次要
應仔細使用具有O(n)性能的集合方法
121、Collection.isEmpty() should be used to test for emptiness
壞味道 次要
應該使用Collection.isEmpty()來測試空集合
122、Comment pattern matcher
壞味道 次要
該規則允許在TODO,NOPMD,...之外的任何類型的內容中找到任何類型的模式,NOSONAR除外
123、Comments Indentation
壞味道 次要
註釋縮進

tokens

tokens to check
默認值
SINGLE_LINE_COMMENT,BLOCK_COMMENT_BEGIN
124、Comments should not be located at the end of lines of code
壞味道 次要
註釋不應位於代碼行的末尾

legalTrailingCommentPattern
Description Pattern for text of trailing comments that are allowed. By default, comments containing only one word.
默認值
^\s*+[^\s]++$
125、Comparators should be "Serializable"
壞味道 嚴重
Comparators should be "Serializable"
126、Conditionals should start on new lines
壞味道 嚴重
條件表達式應該起始新行
127、Constant Name
壞味道 次要
檢查常數名稱是否符合指定的格式
applyToPackage

Controls whether to apply the check to package-private member
默認值
true
format

Regular expression
默認值
^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
applyToPublic

Controls whether to apply the check to public member
默認值
true
applyToProtected
Controls whether to apply the check to protected member
默認值
true
applyToPrivate
Controls whether to apply the check to private member
默認值
true
128、Constant names should comply with a naming convention
壞味道 嚴重
常數名稱應符合命名約定

format

Regular expression used to check the constant names against.
默認值
^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
129、Constants should not be defined in interfaces
壞味道 嚴重
常量不應在接口中定義
130、Constructors should not be used to instantiate "String" and primitive-wrapper classes
壞味道 主要
構造函數不應用於實例化“String”和原始包裝類
131、Constructors should only call non-overridable methods
壞味道 嚴重
構造函數只應該調用不可覆蓋的方法
132、Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply
壞味道 嚴重
控制流程語句“if”,“for”,“while”,“switch”和“try”不能嵌套太深

max

Maximum allowed control flow statement nesting depth.
默認值
3
133、Control structures should use curly braces
壞味道 嚴重
控制結構應使用花括號
134、Covariant Equals
壞味道 嚴重
檢查一個類是否定義了一個協變方法equals,那麼它定義了方法equals(java.lang.Object)
135、Custom Import Order
壞味道 主要
檢查導入聲明組按照用戶指定的順序顯示。 如果有導入,但是在組態中未指定其組,則導入應放在導入列表的末尾。
thirdPartyPackageRegExp

RegExp for THIRDPARTY_PACKAGE group imports.
默認值
^$
separateLineBetweenGroups
Force empty line separator between import groups.
默認值
true
sortImportsInGroupAlphabetically
Force grouping alphabetically.
默認值
false
specialImportsRegExp
RegExp for SPECIAL_IMPORTS group imports.
默認值
^$
customImportOrderRules
List of order declaration customizing by user.
standardPackageRegExp
RegExp for STANDARD_JAVA_PACKAGE group imports.
默認值
java|javax
136、Cyclomatic Complexity
壞味道 主要
檢查針對特定限制的方法的循環複雜性

switchBlockAsSingleDecisionPoint
whether to treat the whole switch block as a single decision point
默認值
false
max

the maximum threshold allowed.
默認值
10
tokens

tokens to check
默認值
LITERAL_WHILE,LITERAL_DO,LITERAL_FOR,LITERAL_IF,LITERAL_SWITCH,LITERAL_CASE,LITERAL_CATCH,QUESTION,LAND,LOR
137、Dead stores should be removed
壞味道 主要
沒用的存儲應該除移
138、Declaration Order
壞味道 提示
聲名的順序
ignoreModifiers

Whether to ignore modifiers
默認值
false
ignoreConstructors
Whether to ignore constructors
默認值
false
139、Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "LinkedList"
壞味道 次要
聲明應該使用Java集合接口,例如“List”,而不是特定的實現類,如“LinkedList”
140、Default annotation parameter values should not be passed as arguments
壞味道 次要
默認註解參數值不應作爲參數傳遞
141、Default Comes Last
壞味道 主要
檢查在switch語句中的所有情況之後的默認值。

skipIfLastAndSharedWithCase
whether to allow default along with case if they are not last
默認值
false
142、Deprecated "${pom}" properties should not be used
壞味道 次要
不應使用不推薦使用的“$ {pom}”屬性
143、Deprecated code should be removed
壞味道 提示
應刪除棄用的代碼
144、Deprecated elements should have both the annotation and the Javadoc tag
壞味道 主要
棄用元素應有註解和doc標籤
145、Descendant Token
壞味道 次要
檢查其他令牌下的限制令牌
maximumMessage
error message when the maximum count is exceeded
maximumDepth

the maximum depth for descendant counts
limitedTokens

set of tokens with limited occurrences as descendants
maximumNumber

a maximum count for descendants
minimumMessage
error message when the maximum count is exceeded
minimumNumber

a minimum count for descendants
minimumDepth

the minimum depth for descendant counts
sumTokenCounts
whether the number of tokens found should be calculated from the sum of the individual token counts
默認值
false
146、Design For Extension
壞味道 次要
擴展設計

ignoredAnnotations
Annotations which allow the check to skip the method from validation.
默認值
Test,Before,After,BeforeClass,AfterClass
147、EJB interceptor exclusions should be declared as annotations
壞味道 阻斷
EJB interceptor exclusions應該以註解的形式使用
148、Empty arrays and collections should be returned instead of null
壞味道 主要
應該返回空數組和集合,而不是null
149、Empty Block
壞味道 主要
Checks for empty blocks
tokens

blocks to check
默認值
LITERAL_WHILE,LITERAL_TRY,LITERAL_FINALLY,LITERAL_DO,LITERAL_IF,LITERAL_ELSE,LITERAL_FOR,INSTANCE_INIT,STATIC_INIT,LITERAL_SWITCH,LITERAL_SYNCHRONIZED
option

policy on block contents
默認值
stmt
150、Empty catch block
壞味道 主要
檢查空的catch塊。 有兩個選項可以使驗證更加精確(默認情況下,檢查允許空的catch塊和任何註釋)

exceptionVariableName
Format of skipping exception''s variable name.
默認值
^$
commentFormat

Format of comment.
默認值
.*
151、Empty For Initializer Pad
壞味道 次要
檢查初始化程序爲空的填充; 那是空的是否需要一個空的初始化程序,或者禁止這樣的空格。 示例:for(; i <j; i ++,j--)

option

policy on how to pad an empty for iterator
152、Empty For Iterator Pad
壞味道 次要
檢查一個空的填充迭代器; 那就是空格是否需要一個空的迭代器,否則這樣的空格是被禁止的。 示例:for(Iterator foo = very.long.line.iterator(); foo.hasNext();)

option

policy on how to pad an empty for iterator
153、Empty Line Separator
壞味道 主要
在標題,包,所有導入聲明,字段,構造函數,方法,嵌套類,靜態初始化器和實例初始化器之後檢查空行分隔符
allowNoEmptyLineBetweenFields

Allow no empty line between fields
默認值
false
allowMultipleEmptyLines
Allows multiple empty lines between class members.
默認值
true
tokens

assignments to check
默認值
PACKAGE_DEF,IMPORT,CLASS_DEF,INTERFACE_DEF,ENUM_DEF,STATIC_INIT,INSTANCE_INIT,METHOD_DEF,CTOR_DEF,VARIABLE_DEF
allowMultipleEmptyLinesInsideClassMembers
Allow multiple empty lines inside class members
默認值
true
154、Empty Statement
壞味道 次要
檢測空的語句(獨立的';')。
155、Empty statements should be removed
壞味道 次要
移除空語句
156、Enumeration should not be implemented
壞味道 主要
不應實同Enumeration
157、Equality operators should not be used in "for" loop termination conditions
壞味道 嚴重
循環終止條件下不應使用平等運算符
158、Equals Avoid Null
壞味道 主要
159、Escaped Unicode characters should not be used
壞味道 主要
不應使用轉義的Unicode字符
160、Exception classes should be immutable
壞味道 次要
異常類應該是不可變的
161、Exception handlers should preserve the original exceptions
壞味道 主要
異常處理程序應保留原始異常
162、Exception types should not be tested using "instanceof" in catch blocks
壞味道 主要
異常類型不應該在catch塊中使用“instanceof”進行測試
163、Exceptions should not be thrown in finally blocks
壞味道 嚴重
異常不應該在finally塊中拋出
164、Executable Statement Count
壞味道 主要
將可執行語句的數量限制爲指定的限制(默認= 30)。

max

the maximum threshold allowed. Default is 30.
默認值
30
tokens

members to check
默認值
CTOR_DEF,METHOD_DEF,INSTANCE_INIT,STATIC_INIT
165、Execution of the Garbage Collector should be triggered only by the JVM
壞味道 嚴重
垃圾收集器的執行只能由JVM觸發
166、Exit methods should not be called
壞味道 阻斷
調用System.exit(int status)或Rutime.getRuntime()。exit(int status)調用關閉掛鉤並關閉整個Java虛擬機。 調用Runtime.getRuntime()。halt(int)立即關閉,而不調用關閉掛鉤,並跳過完成
167、Explicit Initialization
壞味道 主要
檢查任何類或對象成員是否明確地初始化爲其類型值的默認值(對於對象引用爲空,數字類型爲零,對於布爾爲char爲false)。
168、Expressions should not be too complex
壞味道 嚴重
表達式不應太複雜

max

Maximum number of allowed conditional operators in an expression
默認值
3
169、Extensions and implementations should not be redundant
壞味道 次要
擴展和實現不應該是多餘的
170、Fall Through
壞味道 主要
171、Field names should comply with a naming convention
壞味道 次要
字段名稱應符合命名約定
format

Regular expression used to check the field names against.
默認值
^[a-z][a-zA-Z0-9]*$
172、Fields in a "Serializable" class should either be transient or serializable
壞味道 嚴重
“Serializable”類中的字段應該是transient或可序列化的
173、Fields in non-serializable classes should not be "transient"
壞味道 次要
不可序列化類的字段不應該是“transient”
174、Fields should not be initialized to default values
壞味道 次要
不應將字段初始化爲默認值
175、File Contents Holder
壞味道 次要
配置爲TreeWalker子模塊時,保留當前的全局訪問文件內容。 例如,過濾器可以通過此模塊訪問當前文件內容
176、File Length
壞味道 主要
如果源文件變得很長,那麼很難理解。 因此,長類通常應該重構到專注於特定任務的幾個單獨的類中

fileExtensions
file type extension of files to process
max

maximum allowable number of lines. Default is 2000.
177、File Tab Character
壞味道 次要
檢查源代碼中沒有製表符('\ t')

fileExtensions
file type extension of files to process
eachLine

whether to report on each line containing a tab, or just the first instance. Default is false.
178、Files should contain an empty new line at the end
壞味道 次要
文件最後應該包含一個空的新行
179、Files should contain only one top-level class or interface each
壞味道 主要
文件應該只包含一個頂級類或接口
180、Files should not be empty
壞味道 次要
刪除空文件
181、Files should not have too many lines of code
壞味道 主要
源碼文件代碼行數檢查
182、Modifiers should be declared in the correct order
壞味道 次要
Java語言規範建議按以下順序列出修飾符:
1. Annotations
2. public
3. protected
4. private
5. abstract
6. static
7. final
8. transient
9. volatile
10. synchronized
11. native
12. strictfp
183、Sections of code should not be "commented out"
壞味道 主要
不要有注掉的代碼,影響可讀性,可以刪除
184、Strings should not be concatenated using '+' in a loop
壞味道 次要
用StringBuilder代替String拼接
185、String function use should be optimized for single characters
壞味道 主要
字符串方法操作中單字符建議優先用單引號
186、Unused local variables should be removed
壞味道 次要
如果一個局部變量被聲明但未被使用,那麼它是死代碼,應該被刪除。 這樣做會提高可維護性,因爲開發人員不會想知道使用什麼變量
187、The diamond operator ("<>") should be used
壞味道 次要
Java 7引入了操作符(<>)來減少泛型代碼的冗長度。
List<String> strings = new ArrayList<>()
188、Useless imports should be removed
壞味道 次要
不要導入沒有用到的導入
189、Source files should not have any duplicated blocks
壞味道 主要
源文件不應有任何重複塊
190、Only static class initializers should be used
壞味道 主要
靜態代碼塊應加,static標識
191、Generic exceptions should never be thrown
壞味道 主要
通用異常如Error, RuntimeException, Throwable, and Exception不應拋出,應定義和拋出一個專門的異常,而不是使用通用異常
192、Method names should comply with a naming convention
壞味道 次要
方法名稱應符合命名約定
默認規則:^[a-z][a-zA-Z0-9]*$
193、Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used
壞味道 主要
Java API的早期類,例如Vector,Hashtable和StringBuffer已被同步,使其成爲線程安全的。 不幸的是,即使從單個線程使用這些集合,同步也會對性能產生很大的負面影響
194、Standard outputs should not be used directly to log anything
壞味道 主要
用日誌記錄代替標準輸出
195、Local variable and method parameter names should comply with a naming convention
壞味道 次要
局部變量和方法參數名稱應符合命名約定
默認:^[a-z][a-zA-Z0-9]*$
196、Local Variables should not be declared and then immediately returned or thrown
壞味道 次要
聲明一個變量只是立即返回或拋出它是一個糟糕的做法
197、Instance methods should not write to "static" fields
壞味道 嚴重
靜態屬性更新需同步
198、Methods should not be empty
壞味道 嚴重
不要存在空方法
199、Utility classes should not have public constructors
壞味道 主要
幫助類不應該有公共構造函數,幫助類不宜實例化,且應該有一個如下的私有構造方法
private StringUtils() {
throw new IllegalStateException("Utility class");
}
200、Static non-final field names should comply with a naming convention
壞味道 次要
靜態非最終字段名稱應符合命名約定
默認:^[a-z][a-zA-Z0-9]*$
201、Methods returns should not be invariant
壞味道 阻斷
方法返回值不應該是相同的值
202、Return of boolean expressions should not be wrapped into an "if-then-else" statement
壞味道 次要
可以根據boolean表達式就能返回的直接返回boolean表達式,不需要if-then-else語句
203、Try-with-resources should be used
壞味道 嚴重
Try-with-resources代替try-catch-finally
204、String literals should not be duplicated
壞味道 嚴重
重複的字符串文字會使重構過程容易出錯,因爲您必須確保更新所有

threshold

Number of times a literal must be duplicated to trigger an issue
默認值
3
205、

 


壞味道


可調整:


1、Abbreviation As Word In Name (默認 關閉)
壞味道 主要
檢查驗證標識符名稱中的縮寫(連續大寫字母)長度,還允許執行駱駝案例命名
allowedAbbreviationLength 3
6、Annotation Location (默認 關閉)
壞味道 主要
註釋位置
allowSamelineSingleParameterlessAnnotation

To allow single parameterless annotation to be located on the same line as target element.
默認值
true
allowSamelineParameterizedAnnotation
To allow parameterized annotation to be located on the same line as target element.
默認值
false
allowSamelineMultipleAnnotations
To allow annotation to be located on the same line as target element.
默認值
false
tokens

tokens to check
默認值
CLASS_DEF,INTERFACE_DEF,ENUM_DEF,METHOD_DEF,CTOR_DEF,VARIABLE_DEF
7、Annotation Use Style (默認 關閉)
壞味道 主要

trailingArrayComma
Defines the policy for trailing comma in arrays. Default is never.
closingParens

Defines the policy for ending parenthesis. Default is never.
elementStyle

Defines the annotation element styles. Default value is compact_no_array.
8、Artifact ids should follow a naming convention (默認 關閉)
壞味道 次要
共享命名約定允許團隊有效協作。 當pom的artifactId與提供的正則表達式不匹配時,此規則引發了一個問題

regex

The regular expression the "artifactId" should match
默認值
[a-z][a-z-0-9]+
9、At-clause Order (默認 關閉)
壞味道 主要
檢查從句順序
tagOrder
allows to specify the order by tags.
默認值
@author,@version,@param,@return,@throws,@exception,@see,@since,@serial,@serialField,@serialData,@deprecated
target

allows to specify targets to check at-clauses.
10、Avoid Escaped Unicode Characters (默認 關閉)
壞味道 主要
避免轉義的Unicode字符

allowIfAllCharactersEscaped
Allow if all characters in literal are escaped.
默認值
false
allowNonPrintableEscapes
Allow non-printable escapes.
默認值
false
allowByTailComment
Allow use escapes if trail comment is present.
默認值
false
allowEscapesForControlCharacters
Allow use escapes for non-printable(control) characters.
默認值
false
11、Avoid Nested Blocks (默認 關閉)
壞味道 主要
避免嵌套塊
allowInSwitchCase
Allow nested blocks in case statements. Default is false.
12、Avoid Star Import (默認 關閉)
壞味道 次要
檢查發現使用*符號的導入語句
excludes

packages where star imports are allowed. Note that this property is not recursive, subpackages of excluded packages are not automatically excluded.
allowStaticMemberImports
whether to allow starred static member imports like <code>import static org.junit.Assert.*;</code>. Default is false.
默認值
false
allowClassImports
whether to allow starred class imports like <code>import java.util.*;</code>. Default is false.
默認值
false
13、Boolean Expression Complexity (默認 關閉)
壞味道 主要
將嵌套布爾運算符(&&,||和^)限制爲指定的深度(默認= 3)。

max

the maximum allowed number of boolean operations in one expression. Default is 3.
默認值
3
tokens

tokens to check. Default is LAND,BAND,LOR,BOR,BXOR.
默認值
LAND,BAND,LOR,BOR,BXOR
14、Branches should have sufficient coverage by tests (默認 關閉)
壞味道 主要
分支應有足夠的測試覆蓋

minimumBranchCoverageRatio
默認值
65
15、Catch Parameter Name (默認 關閉)
壞味道 主要
檢查catch參數名是否符合format屬性指定的格式

format

Specifies valid identifiers. Default is ^(e|t|ex|[a-z][a-z][a-zA-Z]+)$
默認值
^(e|t|ex|[a-z][a-z][a-zA-Z]+)$
16、Class Data Abstraction Coupling (默認 關閉)
壞味道 主要
度量衡量給定類中其他類的實例化數。

max

the maximum threshold allowed. Default is 7.
excludedClasses
User-configured class names to ignore.
excludeClassesRegexps
User-configured regular expressions to ignore classes
excludedPackages
User-configured packages to ignore
17、Class Fan Out Complexity (默認 關閉)
壞味道 主要
類的依賴類數量

max

the maximum threshold allowed. Default is 20.
excludedClasses
User-configured class names to ignore
excludeClassesRegexps
User-configured regular expressions to ignore classes
excludedPackages
User-configured packages to ignore
18、Class names should comply with a naming convention (開放)
壞味道 次要
類名應符合命名約定

format

Regular expression used to check the class names against.
默認值
^[A-Z][a-zA-Z0-9]*$
19、Classes from "sun.*" packages should not be used (開放)
壞味道 主要
不得使用“sun.*”軟件包的類,sun類*或com.sun *包被視爲實現細節,不屬於Java API

Exclude

Comma separated list of Sun packages to be ignored by this rule. Example: com.sun.jna,sun.misc
20、Classes should not be coupled to too many other classes (Single Responsibility Principle) (默認 關閉)
壞味道 主要
類不應與太多其他類(單一責任原則)相耦合(依賴)

max

Maximum number of classes a single class is allowed to depend upon
默認值
20
21、Classes should not be too complex (默認 關閉)
壞味道 嚴重 廢棄
類不應太複雜

max

Maximum complexity allowed.
默認值
200
22、Classes should not have too many "static" imports (默認 關閉)
壞味道 主要
靜態導入類允許您使用其公共靜態成員,而不必使用類名。 這可以很方便,但如果靜態導入太多的類,你的代碼可能會變得混亂,很難維護

threshold

The maximum number of static imports allowed
默認值
4
23、Classes should not have too many fields (默認 關閉)
壞味道 主要
類不應有太多字段
countNonpublicFields
Whether or not to include non-public fields in the count
默認值
true
maximumFieldThreshold
The maximum number of fields
默認值
20
24、Classes should not have too many methods (默認 關閉)
壞味道 主要
類不應該有太多方法

countNonpublicMethods
Whether or not to include non-public methods in the count.
默認值
true
maximumMethodThreshold
The maximum number of methods authorized in a class.
默認值
35
25、Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line (默認 關閉)
壞味道 次要
關閉大括號,下一個“else”,“catch”和“finally”關鍵字應位於同一行
26、Close curly brace and the next "else", "catch" and "finally" keywords should be on two different lines (默認 關閉)
壞味道 次要
關閉大括號和下一個“else”,“catch”和“finally”關鍵字應該在兩個不同的行
29、Comments should not be located at the end of lines of code (默認 關閉)
壞味道 次要
註釋不應位於代碼行的末尾

legalTrailingCommentPattern
Description Pattern for text of trailing comments that are allowed. By default, comments containing only one word.
默認值
^\s*+[^\s]++$
30、Constant Name (默認 關閉)
壞味道 次要
檢查常數名稱是否符合指定的格式
applyToPackage
Controls whether to apply the check to package-private member
默認值
true
format

Regular expression
默認值
^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
applyToPublic

Controls whether to apply the check to public member
默認值
true
applyToProtected
Controls whether to apply the check to protected member
默認值
true
applyToPrivate
Controls whether to apply the check to private member
默認值
true
31、Control flow statements "if", "for", "while", "switch" and "try" should not be nested too deeply (默認 關閉)
壞味道 嚴重
控制流程語句“if”,“for”,“while”,“switch”和“try”不能嵌套太深

max

Maximum allowed control flow statement nesting depth.
默認值
3
32、Custom Import Order (默認 關閉)
壞味道 主要
檢查導入聲明組按照用戶指定的順序顯示。 如果有導入,但是在組態中未指定其組,則導入應放在導入列表的末尾。
thirdPartyPackageRegExp

RegExp for THIRDPARTY_PACKAGE group imports.
默認值
^$
separateLineBetweenGroups
Force empty line separator between import groups.
默認值
true
sortImportsInGroupAlphabetically
Force grouping alphabetically.
默認值
false
specialImportsRegExp
RegExp for SPECIAL_IMPORTS group imports.
默認值
^$
customImportOrderRules
List of order declaration customizing by user.
standardPackageRegExp
RegExp for STANDARD_JAVA_PACKAGE group imports.
默認值
java|javax
33、Cyclomatic Complexity (默認 關閉)
壞味道 主要
檢查針對特定限制的方法的循環複雜性

switchBlockAsSingleDecisionPoint
whether to treat the whole switch block as a single decision point
默認值
false
max

the maximum threshold allowed.
默認值
10
tokens

tokens to check
默認值
LITERAL_WHILE,LITERAL_DO,LITERAL_FOR,LITERAL_IF,LITERAL_SWITCH,LITERAL_CASE,LITERAL_CATCH,QUESTION,LAND,LOR
34、Default Comes Last (默認 關閉)
壞味道 主要
檢查在switch語句中的所有情況之後的默認值。

skipIfLastAndSharedWithCase
whether to allow default along with case if they are not last
默認值
false
35、Empty catch block (默認 關閉)
壞味道 主要
檢查空的catch塊。 有兩個選項可以使驗證更加精確(默認情況下,檢查允許空的catch塊和任何註釋)

exceptionVariableName
Format of skipping exception''s variable name.
默認值
^$
commentFormat

Format of comment.
默認值
.*
36、Empty For Initializer Pad (默認 關閉)
壞味道 次要
檢查初始化程序爲空的填充; 那是空的是否需要一個空的初始化程序,或者禁止這樣的空格。 示例:for(; i <j; i ++,j--)

option

policy on how to pad an empty for iterator
37、Empty For Iterator Pad
壞味道 次要
檢查一個空的填充迭代器; 那就是空格是否需要一個空的迭代器,否則這樣的空格是被禁止的。 示例:for(Iterator foo = very.long.line.iterator(); foo.hasNext();)

option

policy on how to pad an empty for iterator
38、Empty Line Separator (默認 關閉)
壞味道 主要
在標題,包,所有導入聲明,字段,構造函數,方法,嵌套類,靜態初始化器和實例初始化器之後檢查空行分隔符
allowNoEmptyLineBetweenFields

Allow no empty line between fields
默認值
false
allowMultipleEmptyLines
Allows multiple empty lines between class members.
默認值
true
tokens

assignments to check
默認值
PACKAGE_DEF,IMPORT,CLASS_DEF,INTERFACE_DEF,ENUM_DEF,STATIC_INIT,INSTANCE_INIT,METHOD_DEF,CTOR_DEF,VARIABLE_DEF
allowMultipleEmptyLinesInsideClassMembers
Allow multiple empty lines inside class members
默認值
true
39、Executable Statement Count (默認 關閉)
壞味道 主要
將可執行語句的數量限制爲指定的限制(默認= 30)。

max

the maximum threshold allowed. Default is 30.
默認值
30
tokens

members to check
默認值
CTOR_DEF,METHOD_DEF,INSTANCE_INIT,STATIC_INIT
40、Expressions should not be too complex (默認 關閉)
壞味道 嚴重
表達式不應太複雜

max

Maximum number of allowed conditional operators in an expression
默認值
3
42、File Length (默認 關閉)
壞味道 主要
如果源文件變得很長,那麼很難理解。 因此,長類通常應該重構到專注於特定任務的幾個單獨的類中

fileExtensions
file type extension of files to process
max

maximum allowable number of lines. Default is 2000.
43、File Tab Character (默認 關閉)
壞味道 次要
檢查源代碼中沒有製表符('\ t')

fileExtensions
file type extension of files to process
eachLine

whether to report on each line containing a tab, or just the first instance. Default is false.
44、Files should contain an empty new line at the end (默認 關閉)
壞味道 次要
文件最後應該包含一個空的新行

 


已調整:


1、String literals should not be duplicated (調整)
壞味道 嚴重
重複的字符串文字會使重構過程容易出錯,因爲您必須確保更新所有

threshold

Number of times a literal must be duplicated to trigger an issue
默認值
3 調整爲 5

 

 


已關閉:


1、Utility classes should not have public constructors (關閉)
壞味道 主要
幫助類不應該有公共構造函數,幫助類不宜實例化,且應該有一個如下的私有構造方法
private StringUtils() {
throw new IllegalStateException("Utility class");
}
2、Methods returns should not be invariant (關閉)
壞味道 阻斷
方法返回值不應該是相同的值
3、Return of boolean expressions should not be wrapped into an "if-then-else" statement (關閉)
壞味道 次要
可以根據boolean表達式就能返回的直接返回boolean表達式,不需要if-then-else語句
4、The diamond operator ("<>") should be used (關閉) jdk7+可用
壞味道 次要
Java 7引入了操作符(<>)來減少泛型代碼的冗長度
5、Sections of code should not be "commented out" (關閉)
壞味道 主要
不要有注掉的代碼,影響可讀性,可以刪除
6、Try-with-resources should be used (關閉) jdk7+可用
壞味道 嚴重
Try-with-resources代替try-catch-finally
7、Loops should not be infinite (關閉)
Bug 阻斷
循環不應該是無限的
8、Credentials should not be hard-coded (關閉)
漏洞 阻斷
憑證不應該硬編碼
9、Anonymous inner classes containing only one method should become lambdas (關閉)
壞味道 主要
只有一個方法的匿名內部類應該變成lambdas
10、"throws" declarations should not be superfluous (關閉) 拋出運行時異常,有的框架接口即拋出此類異常
壞味道 次要
“拋出”聲明不應該是多餘的
11、IP addresses should not be hardcoded (關閉)
漏洞 次要
ip 地址不應該硬編碼
12、"@Override" should be used on overriding and implementing methods (關閉)
壞味道 主要
重寫的和實現在方法要加Override標註
13、An open curly brace should be located at the beginning of a line (關閉)
壞味道 次要
開放的大括號應位於一行的開頭
14、Cognitive Complexity of methods should not be too high (關閉)
壞味道 嚴重
認知複雜度是衡量一種方法的控制流程難以理解的度量。 認知複雜性較高的方法難以維持。
Threshold
The maximum authorized complexity.
默認值

各位看官大佬,不足之處,多多批評指正,不勝感激!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章