簡體   English   中英

SonarLint 在這里使用原始的 boolean 表達式

[英]SonarLint Use the primitive boolean expression here

我有以下 class 屬性:

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 希望您確保沒有任何空指針異常,或者至少這也是我在嘗試驗證變量之前進行檢查時所看到的:

如果我有下一個,聲納會抱怨

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

但是如果我添加一個針對空值的快速驗證,Sonar 就會停止抱怨它

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

現在,正如您提到的,您可以使用 Boolean 類來使用下一個

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

作為

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

聽起來它對 Java 來說太冗長了但在內部,他們檢查對象是否是實例布爾值,因此他們放棄為空的可能性,如下所述: 在調用 instanceof 之前是否需要空檢查?

您可以從 git repo 中檢查它接受的內容和不接受的內容:

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

嘗試 .booleanValue() 像這樣 if(properties.getEnabled().booleanValue()) { } 希望它會幫助你。

使用 org.apache.commons.lang3.BooleanUtils,這是一個空安全的方式:

if (BooleanUtils.isNotTrue(properties.getEnabled())) {
    return true;
}

這似乎有一個簡單的答案。 如果該屬性可以為空,那么 getter 的理智應該會有所幫助。

class Properties {
    private Boolean enabled;

    public Boolean isEnabled() {
        return enabled == true;
    }
}

嘗試這個 :

public boolean x (){ 
    boolean prop=properties.getEnabled() 
    if (prop) { 
        return true; 
    }else return false; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM