这次改sonar一共400多个严重问题,很多易犯共性的地方整理如下:
- Either log or rethrow this exception——异常处理
200多个此类问题!
Noncompliant Code Example:
(1) Nested blocks of code should not be left empty
try {
业务代码
} catch (Exception e) {
//null
}
(2) Throwable.printStackTrace(...) should not be called0 —— Use a logger to log this exception
try {
业务代码
} catch (Exception e) {
e.printStackTrace();
}
(3) Exception handlers should preserve the original exceptions
try {
业务代码
} catch (Exception e) {
logger.error("send failed" + e.getMessage());
}
>>>
Compliant Solution:
try {
业务代码
} catch (Exception e) {
ExceptionsHelper.errorMessage("send failed ", e);
}
- "public static" fields should be constant——公共静态成员应该加上final
70多个此类问题!
Noncompliant Code Example:
public static String TYPE_NAME_METADATA = "大数据元数据";
>>>
Compliant Solution:
public static final String TYPE_NAME_METADATA = "大数据元数据";
- Math operands should be cast before assignment——数字操作在操作或赋值前要转化
Noncompliant Code Example:
long t = 12 * 60 * 60 * 1000;
>>>
Compliant Solution:
long t = 12 * 60 * 60 * 1000L;
- makes inefficient use of keySet iterator instead of entrySet iterator——用keySet 方式遍历Map的性能不如entrySet性能好
Noncompliant Code Example:
for (Long key : map.keySet()) {
}
>>>
Compliant Solution:
for (Entry<Long, Long> entry : map.entrySet()) {
}
- Use isEmpty() to check whether the collection is empty or not. ——集合的是否为空集合的判断
Noncompliant Code Example:
if (myCollection.size() == 0) {
}
>>>
Compliant Solution:
if (myCollection.isEmpty()) {
}
-
Dead stores should be removed——没用的存储应该除移
-
Nullcheck of value previously dereferenced——多余的null检查;前边废弃null值检查的
System system = systemRepository.findOne(rel.getSystemId());
system.setLicence(null);
if (system == null || system.getId() == null) {
continue;
}
>>>
System system = systemRepository.findOne(rel.getSystemId());
if (system == null || system.getId() == null) {
continue;
}
system.setLicence(null);
- Move the "0" string literal on the left side of this string comparison.——字符串比较的左边放常量,右边放变量
String myString = null;
System.out.println("Equal? " + myString.equals("foo"));
>>>
System.out.println("Equal?" + "foo".equals(myString));
- Load of known null value——加载已知是null的值
if (topicId == null) {
logger.error("havingRelationTopic fail topicId:" + topicId + " is null ");
return false;
}
>>>
if (topicId == null) {
logger.error("havingRelationTopic fail! topicId is null ");
return false;
}
- Method invokes inefficient Number constructor; use static valueOf instead——Integer.ValueOf(int)的效率比Integer(int)快大约3.5倍
new Integer(offsetData.size()).equals(counts)
>>>
Integer.valueOf(offsetData.size()).equals(counts)
网友评论