Java

Java

Made by DeepSource

Method with Optional return type must not return null JAVA-S0031

Bug risk
Critical

The usage of an Optional return type (java.util.Optional or com.google.common.base.Optional for Java 7) always means that explicit null returns were not desired by design.

Examples

Bad Practice

public Optional<Boolean> checkSomething() {
    Optional<Boolean> retVal = null;

    if (something) {
        boolean boolValue = ...;
        retVal = Optional.of(boolValue);
    }

    return retVal; // May be null!
}

Returning a null value in such a case is a contract violation and will most likely break client code. In addition, this introduces the danger of encountering a null pointer exception in scenarios which expressly wish to prevent them.

Always initialize Optionals with the value returned by Optional.empty() instead of initializing to null:

Recommended

Optional<Boolean> retVal = Optional<>.empty();

if (something) {
    boolean boolValue = ...;
    retVal = Optional.of(boolValue);
}

return retVal; // retVal is now either empty or boolean valued; never null.

References