sonar代码扫描常见问题以及处理⽅案sonar代码扫描常见问题以及处理⽅案
)
⼀. 没有关闭io流
sonar
Use try-with-resources or close this"FileInputStream" in a "finally" clause.
错误⽰例
FileInputStream fis = null;
byte[] buffer =new byte[1024];
try{
fis =new FileInputStream(new File("E:\Java⽂件.txt"));
ad(buffer)>0){
System.out.println(new String(buffer));
}
}catch(Exception e){
e.printStackTrace();
}
解决办法
在catch后加上关闭代码
finally{
if(null != printwriter){
printwriter.close();
bigdecimal取值范围}
}
使⽤try-with-resources ,放在try⾥⾯
try( Fil eInputStream fis =new FileInputStream(new File("E:\Java⽂件.txt"))){
out2.println("the text");
}catch(IOException e){
e.printStackTrace();
}
注: 要是使⽤的是idea ,可以使⽤ctrl + alt + T ,到try-with-resources 快捷解决
⼆. 在finally语句块中有return,continue,throw 语句
sonar
Remove this return statement from this finally block.
Remove this continue statement from this finally block.
Remove this throw statement from this finally block.
错误⽰例
}finally{
try{
fis.close();
}catch(IOException e){
<("关闭流出现异常:{}", e);
throw new Exception();
}
}
解决办法
}finally{
fis.close();
}
三. 可能存在空指针异常,需要增加空值检测。
sonar
A "NullPointerException" could be thrown;"name" is nullable here
错误⽰例
String name = Name();
解决办法
String name ;
if(user != null ){
name = Name();
}
四. 当包含操作状态代码时,不应该忽略⽂件删除操作的结果sonar
Do something with the "boolean" value returned by "delete".
错误⽰例
file.dekete();
解决办法
if(!file.delete()){
// file delete failed; take appropriate action
}
五. 移除没有⽤到的包、变量、⽅法
sonar
//移除没有⽤到的包、变量、⽅法
Remove this useless assignment to local variable xxx
错误⽰例
解决办法
需要看看这个变量有什么作⽤,没有作⽤的可以删除掉
六. ⽅法的认知复杂性不应太⾼
sonar
//⽅法的认知复杂性不应太⾼
Cognitive Complexity of methods should not be too high
//认知复杂性是衡量⼀种⽅法的控制流程理解难度的指标。认知复杂性⾼的⽅法难以别的开发⼈员去维护。
Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to mai ntain.
错误⽰例
解决办法
Compliant Solution(统⼀解决⽅案):
对应这种if-else 过多⽅法,我们主要⽬的是要消除 if-else ,每多⼀个 else 那么就会多⼀个逻辑分叉,代码的易读性会急速降低,这⾥收集总结了⼀些地址,需要的同学可以去看⼀下:
.
七. BigDecimal的取值⽅法
sonar
//BigDecimal的取值⽅法
Use "BigDecimal.valueOf" instead.
错误⽰例
double d =1.1;
BigDecimal bd1 =new BigDecimal(d);// Noncompliant; see comment above
BigDecimal bd2 =new BigDecimal(1.1);// Noncompliant; same result
解决办法
double d =1.1;
BigDecimal bd1 = BigDecimal.valueOf(d);
BigDecimal bd2 = BigDecimal.valueOf(1.1);
⼋. 更改此条件,以便它不总是评估为“false"
sonar
//更改此条件,以便它不总是评估为“false"
Change this condition so that it does not always evaluate to “false”
错误⽰例
解决办法
可以把这⾏删除掉,obj不可能为null if (obj == null) return false; 这样这个bug也没有了。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论