sonar常见bug类型及解决方法

sonar常见bug类型及解决方法(持续更新)

NullPointerException might be thrown as ‘XXX’ is nullable here

说明:未做非空校验,可能产生空指针
解决方案:加上非空校验

Use a “double” or “BigDecimal” instead.

说明:两个float计算会产生不精确的结果
解决方案:将float换为double或者BigDecimal计算
举例:
float a = 16777216.0f;
float b = 1.0f;
float c = a + b; // Noncompliant; yields 1.6777216E7 not 1.6777217E7
double d = a + b; // Noncompliant; addition is still between 2 floats
换为

float a = 16777216.0f;
float b = 1.0f;
BigDecimal c = BigDecimal.valueOf(a).add(BigDecimal.valueOf(b));
double d = (double)a + (double)b;

Cast one of the operands of this multiplication operation to a “long”

说明:int数运算最终再把结果转为long将有可能产生溢出
解决方案:转换为long型预算
举例:

long bigNum = Integer.MAX_VALUE + 2; // Noncompliant. Yields -2147483647
换为

long bigNum = Integer.MAX_VALUE + 2L;

Close this “XXX”.

说明:流没有显示的关闭。
解决方案:在fianlly语句块内关闭。
Remove or correct this useless self-assignment.
说明:缺少this
解决方案:用this.xxx=xxx来替代
举例:
public void setName(String name) {
name = name;
}
换为

public void setName(String name) {
this.name = name;
}

Correct this “&” to “&&”.

说明:错误的使用&和&&
解决方案:根据情况使用&和&&

This branch can not be reached because the condition duplicates a previous condition in the same sequence of “if/else if” statements

说明:if else if 语句判断条件重复
解决方案:去掉多余的判断条件

Make this “XXX” field final.

说明:将某个字段置为final,常见在Exception的参数
解决方案:将字段置为final

Remove this call to “equals”; comparisons between unrelated types always return false.

说明:去掉equals判断语句,因为总为false
解决方案:去掉equals语句

Remove this return statement from this finally block.

说明:在finally语句块中有return语句
解决方案:去掉finally语句块的return语句或者放在finally语句块之外

Remove this continue statement from this finally block.

说明:在finally语句块中有continue语句
解决方案:去掉finally语句块中的continue语句或者放在finally语句块之外

Equality tests should not be made with floating point values.

说明:浮点数之间用 == 来比较大小不准确
解决方案:用Number或者BigDecimal来比较
举例:
float myNumber = 3.146;
if ( myNumber == 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be false
// …
}
if ( myNumber != 3.146f ) { //Noncompliant. Because of floating point imprecision, this will be true
// …
}

Add a type test to this method.

说明:强转前未判断类型
解决方案:强转前先判断类型
举例:
ErpVO ev = (ErpVO) obj;
return this.userCode.equals(ev.getUserCode());

换为

if (obj == null) {

return false;

}

if (obj.getClass() != this.getClass()) {

return false;

}

Add an end condition to this loop.

说明:没有退出条件

解决方案:根据情况来决定方法的退出条件

Make “XXX” an instance variable.

说明:有些类不是线程安全的,将变量生命为静态的可能会导致线程安全问题
解决方案:将变量声明为实例的。


版权声明:本文为asdasd3418原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。