gpt4 book ai didi

java - SonarLint 此处使用原始 boolean 表达式

转载 作者:行者123 更新时间:2023-11-30 05:23:52 25 4
gpt4 key购买 nike

我有以下类属性:

class Properties {
private Boolean enabled;

public Boolean getEnabled() {
return enabled;
}
}

如果我编写以下代码,SonarLint 会在 if 条件上向我发出警告,提示“此处使用原始 boolean 表达式。”。

if (!properties.getEnabled()) {
return true;
}
// more code

将 if 条件更改为以下内容可关闭警告。但可读性较差,这不是 SonarLint 想要的,或者?

if (properties.getEnabled().equals(Boolean.FALSE)) {
return true;
}
// more code

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

最佳答案

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

如果我有下一个代码,Sonar 会发出警告,指出该代码可能引发空指针异常。

if (properties.getEnabled()) {
// Your code
}

但是如果我添加针对空值的快速验证,Sonar 就会停止提示:

if (properties.getEnabled() != null && properties.getEnabled()) {
// Your code
}

现在,正如您所提到的,您可以使用 Boolean 类来比较 boolean 值,如下代码所示:

Boolean.TRUE.equals(properties.getEnabled());

您可以将其放在 if 语句中,如下代码所示:

if (Boolean.TRUE.equals(properties.getEnabled())){
// Your code
}

这可能看起来太冗长,但 Boolean.TRUE.equals() 的实现会检查对象是否是 Boolean 类的实例,并且 null 不能是任何类的实例,因为 null 不是实例。您可以在这里找到更好的解释:Is null check needed before calling instanceof?

他们曾经有一套非常好的和简单的测试来了解我第一次回答这个问题时在这个答案中发布的内容和不接受的内容,但看起来它不再存在于 master 中(我仍然添加它)为了更容易理解,但这是旧版本的声纳,因此只能用作引用):https://github.com/SonarSource/sonar-java/blob/5.14.0.18788/java-checks/src/test/files/checks/BoxedBooleanExpressionsCheck.java

您也可以在此处引用此规则的实现代码:https://github.com/SonarSource/sonar-java/blob/master/java-checks/src/main/java/org/sonar/java/checks/BoxedBooleanExpressionsCheck.java#L131

关于java - SonarLint 此处使用原始 boolean 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59035202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com