常见sonar问题

这次改sonar一共400多个严重问题,很多易犯共性的地方整理如下:
  1. 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);
}
  1. “public static” fields should be constant——公共静态成员应该加上final70多个此类问题!
Noncompliant Code Example:
public static String TYPE_NAME_METADATA = "大数据元数据";
>>>
Compliant Solution:
public static final String TYPE_NAME_METADATA = "大数据元数据";
  1. Math operands should be cast before assignment——数字操作在操作或赋值前要转化
Noncompliant Code Example:
long t = 12 * 60 * 60 * 1000;

>>>
Compliant Solution:
long t = 12 * 60 * 60 * 1000L;
  1. 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()) {
}
  1. Use isEmpty() to check whether the collection is empty or not. ——集合的是否为空集合的判断
Noncompliant Code Example:
if (myCollection.size() == 0) { 
}
>>>
Compliant Solution:
if (myCollection.isEmpty()) {
}
  1. Dead stores should be removed——没用的存储应该除移

  2. 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);
  1. 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));
  1. 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;
}
  1. 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)
    原文作者:MoMeaker
    原文地址: https://www.jianshu.com/p/7d5311b89a8c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞