Bootstrap

sonar常见bug类型及解决方法

sonar常见bug类型及解决方法

1.Use isEmpty() to check whether the collection is empty or not.

解释:
建议使用list.isEmpty()方法 替代list.size()==0 或者 !list.isEmpty() 替代 list.size() >0
修改前

if(attachedColumns.size() > 0) 

修改后

if(attachedColumns.isEmpty()) 

2.Remove this expression which always evaluates to “true”

解释:
建议移除变量值一直是true,没有变化的值
修改前

boolean columnExisted = false;
boolean groupExisted = false;
for(String id : columnIds) {
    String[] idTemp = id.split("\\.");
    String groupCode = idTemp[idTemp.length == 3 ? 1 : 0];
    if(targetGroupCode.equals(groupCode)) groupExisted = true;
}
if(!columnExisted && groupExisted)

修改后

boolean columnExisted = false;
boolean groupExisted = false;
for(String id : columnIds) {
    String[] idTemp = id.split("\\.");
    String groupCode = idTemp[idTemp.length == 3 ? 1 : 0];
    if(targetGroupCode.equals(groupCode)) groupExisted = true;
}
if(groupExisted)

3.Replace this “Map.get()” and condition with a call to “Map.computeIfAbsent()”.

解释:
建议使用Map.computeIfAbsent() 方法替代Map.get() 方法,computeIfAbsent()方法对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中
修改前

List<Node> relatedReports = reportIdMappingTable.get(reportId);
if(relatedReports == null) {
    relatedReports = new LinkedList<>();
    reportIdMappingTable.put(reportId,relatedReports);
}
relatedReports.add(new Node(targetNode,report));

修改后

List<Node> relatedReports =reportIdMappingTable
.computeIfAbsent(reportId, 
(Function<? super String, ? extends List<Node>>) new LinkedList<Node>());
relatedReports.add(new Node(targetNode,report));

4.Provide the parametrized type for this generic.

解释:
建议创建对象时添加默认参数类型
修改前

 Map<String,List<Node>> reportIdMappingTable = new LinkedHashMap();

修改后

Map<String,List<Node>> reportIdMappingTable = new LinkedHashMap<String,List<Node>>();

5.Iterate over the “entrySet” instead of the “keySet”

解释:
建议使用entrySet 替代 keySet,通过查看源代码发现,调用方法keySetMap.keySet()会生成KeyIterator迭代器,其next方法只返回其key值,而调用entrySetMap.entrySet()方法会生成EntryIterator 迭代器,其next方法返回一个Entry对象的一个实例,其中包含key和value。所以当我们用到key和value时,用entrySet迭代性能更高
修改前

public void doSomethingWithMap(Map<String,Object> map) {
  for (String key : map.keySet()) {  
    Object value = map.get(key); 
  }
}

修改后

public void doSomethingWithMap(Map<String,Object> map) {
  for (Map.Entry<String,Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
  }
}

6.2 duplicated blocks of code must be removed.

解释:
有2段重复代码块建议删除
修改前

修改后

7.Replace this use of System.out or System.err by a logger.

解释:
建议使用logger日志输出替代控制台打印system.out.println();
修改前

System.out.println("My Message"); 

修改后

logger.log("My Message");

8.Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.

解释:
添加一个嵌套注释,解释为什么这个方法是空的,抛出UnsupportedOperationException,或者完成这个实现
修改前

public void doSomething() {
}

修改后

public void doSomething() {
  // Do nothing because of X and Y.
}

9.Remove the parentheses around the “x” parameter

解释:
移除最外成括号
修改前

(x) -> x * 2

修改后

x -> x * 2

10.Define and throw a dedicated exception instead of using a generic one.

解释:
定义并引发专用异常,而不是使用泛型异常
修改前

public void foo(String bar) throws Throwable {  
  throw new RuntimeException("My Message");     
}

修改后

public void foo(String bar) {
  throw new MyOwnRuntimeException("My Message");
}

11.Rename this field “LOG” to match the regular expression “[a-z][a-zA-Z0-9]*$”

解释:
重命名成符合命名规则(’[a-z][a-zA-Z0-9]*$’)的属性名称
修改前

class MyClass {
   private int my_field;
}

修改后

class MyClass {
   private int myField;
}

12.Replace “@RequestMapping(method = RequestMethod.GET)” with “@GetMapping”.

解释:
建议使用@GetMapping替换@RequestMapping(method = RequestMethod.GET)
修改前

@RequestMapping(path = "/greeting", method = RequestMethod.GET) 
public Greeting greeting(@RequestParam(value = "name") String name) {
...
}

修改后

@GetMapping(path = "/greeting") 
public Greeting greeting(@RequestParam(value = "name") String name) {
...
}

13.Define a constant instead of duplicating this literal “action1” 3 times.

解释:
建议定义个字符串常量值替代出现引用3次的字符串
修改前

public void run() {
  prepare("action1");                           
  execute("action1");
  release("action1");
}

修改后

private static final String ACTION_1 = "action1";  
public void run() {
  prepare(ACTION_1);                             
  execute(ACTION_1);
  release(ACTION_1);
}

14.Extract this nested ternary operation into an independent statement.

解释:
建议将此嵌套的三元操作提取到独立语句中
修改前

public String getReadableStatus(Job j) {
  return j.isRunning() ? "Running" : j.hasErrors() ? "Failed" : "Succeeded"; 
}

修改后

public String getReadableStatus(Job j) {
  if (j.isRunning()) {
    return "Running";
  }
  return j.hasErrors() ? "Failed" : "Succeeded";
}

15.Add a private constructor to hide the implicit public one.

解释:
如果一个类的里面的方法都是static修饰的静态方法,那么需要给这个类定义一个非公共构造函数(添加私有构造函数以隐藏隐式公共构造函数)
修改前

class StringUtils { 
  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }
}

修改后

class StringUtils {
  private StringUtils() {
    throw new IllegalStateException("Utility class");
  }
  public static String concatenate(String s1, String s2) {
    return s1 + s2;
  }
}
;