Home > Enterprise >  Could be in Optional really anything
Could be in Optional really anything

Time:08-25

I found implemented this code (method where this part of code is used is returning Optional<File>, this part of code had to be added for verification if values are correct and case can be saved):

if (!CaseChecker.checkValues(case)) {
    return Optional.of(new File("FALSE"));
}

When I asked the person, why he is returning something like this. The answer was "Optional can contain any value". To be honest I don't agree with this, because type of Optional is for some reason. So I wanted to confirm if Optional can be really anything and if yes, then what's the reason to write Optional type.

CodePudding user response:

The whole point of Optional is to avoid the situation where you return a bogus value (like null, or like returning -1 from String.indexOf in order to indicate it didn't find anything), putting the responsibility on the caller to know what is bogus and to know to check for it. Returning Optional lets the caller know it needs to check whether a valid result came back, and it takes away the burden of the caller code needing to know what return values aren't valid.

Optional was never meant as a wrapper for a bogus value.

And yes you can return anything. The api doesn't stop you from doing nonsensical things.

Return Optional.empty() if you don't have a valid value to return.

  • Related