Java

Java

Made by DeepSource

Boolean method may return null JAVA-S0030

Bug risk
Major

A method with a Boolean return type returns an explicit null. This is likely intentional, but be aware that API consumers may not realize that.

Examples

Bad Practice

public Boolean checkSomething() {
    if (something) {
        boolean boolValue = ...;
        return boolValue;
    } else return null;
}

If this is intended, such as when interfacing with a database, ensure that the behavior is well documented to avoid confusion. In most cases, it is better to use the native boolean type instead of the Boolean wrapper type to avoid accidents.

A better alternative would be to use the Optional type introduced in Java 8.

Recommended

public Optional<Boolean> checkSomething() {
    if (something) {
        boolean boolValue = ...;
        return Optional.of(boolValue);
    } else return Optional.empty();
}

References