Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sonar Null Caution "null returned but Boolean expected"

How I can edit this code block as a readable or logical way so that I don't get a warning from sonar? I need three result false, true or null

 public Boolean x() {
    if (...) {
        return true;
    } else if (...) {
        return false;
    } else {
        return null;
    }
}
like image 560
Yasin Avatar asked Dec 06 '25 04:12

Yasin


1 Answers

Starting with Java 8 use Optional to codify TRUE, FALSE, Optional.empty. It follows the pattern "avoid returning null" and will at the same time suppress the SonarQube warning.

The code would be

public Optional<Boolean> x() { 
    if (...) { 
       return Optional.of(Boolean.TRUE); 
    } 
    else if (...) { 
       return Optional.of(Boolean.FALSE); 
    } 
    else { 
       return Optional.empty(); 
    } 
} 
like image 99
Marcel Baumann Avatar answered Dec 08 '25 19:12

Marcel Baumann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!