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.
>Solution :
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.) 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.