javajavaoptions

Is this Good Code and Use of Java Option


Is this good code style and good use of Option? This doesn't seem right because the method returns a Generics but the body does not make use of a Generics return. Also, 'smells' a bit bad because of the IF statement.

public Optional<MyObjectType> readData() {
    MyObjectType[] myArray = // Will not be null, but maybe Size 0.
    if(myArray.length > 0)
        return Optional.of(myArray[0]);

    return Optional.of(null);
}

On the client side I have:

public void clientCode() {
    Optional<CurrencyPointData> oData = readCurrency(Currency.ADA);
    if(oData.isPresent()) {
        CurrencyPointData data = oData.get();
        // Use data object
    }
}

Which also doesn't seem to be much better than a normal if(oData == null) check.

Consequently, this code seems rubbish, so should I not be using Optional??


Solution

  • Your client code showcases the purpose of Optional.

    It encourages code to check isPresent() before calling get(), highlighting the issue that there may be no value, unlike simply using CurrencyPointData without Optional, where it's then undefined whether return value can be null. Sure, you can document whether method can return null, but that's not apparent in the code, and we all know that people rarely reads the documentation in detail.

    With Optional you explicitly say that value may be missing.

    That is why Optional is better than simple null check.