Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Could be in Optional really anything

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading