SonarLint 在此处使用原始布尔表达式

fin*_*usl 10 java primitive-types sonarlint

我有以下类属性:

class Properties {
    private Boolean enabled;

    public Boolean getEnabled() {
        return enabled;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我编写以下代码,SonarLint 会在 if 条件上给我一个警告,说“在此处使用原始布尔表达式。”。

if (!properties.getEnabled()) {
    return true;
}
// more code
Run Code Online (Sandbox Code Playgroud)

将 if 条件更改为以下内容会关闭警告。但那不太可读,那不可能是 SonarLint 想要的,或者?

if (properties.getEnabled().equals(Boolean.FALSE)) {
    return true;
}
// more code
Run Code Online (Sandbox Code Playgroud)

SonarLint 到底想让我在这里做什么?问题是什么?

Dam*_*nio 15

正如其他人已经提到的,Sonar 希望您确保没有任何空指针异常,或者至少这也是我在尝试验证变量之前进行检查时所看到的:

如果我有下一个,声纳会抱怨

if (properties.getEnabled()) {
       // Your code
}
Run Code Online (Sandbox Code Playgroud)

但是如果我添加一个针对空值的快速验证,Sonar 就会停止抱怨它

if (properties.getEnabled() != null && properties.getEnabled()) {
       // Your code
}
Run Code Online (Sandbox Code Playgroud)

现在,正如您提到的,您可以使用 Boolean 类来使用下一个

Boolean.TRUE.equals(properties.getEnabled());
Run Code Online (Sandbox Code Playgroud)

作为

if (Boolean.TRUE.equals(properties.getEnabled())){
       // Your code
}
Run Code Online (Sandbox Code Playgroud)

听起来它对 Java 来说太冗长了但在内部,他们检查对象是否是实例布尔值,因此他们放弃为空的可能性,如下所述:在调用 instanceof 之前是否需要空检查?

您可以从 git repo 中检查它接受的内容和不接受的内容:

https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/test/files/checks/BoxedBooleanExpressionsCheck.java