What is the real benefit of returning an optional <Map <String, String >>, and not just an empty Map <String, String>

If my code returns Map<String, String> sure, but may be empty. Does it make sense to convert it to return Optional<Map<String, String>> . Can it add any benefit to empty but not null instances?

+5
source share
1 answer

Like many subjects in computer programming, it depends (tm).

The way I use the option is an alternative to null (in a nutshell). One of its advantages is that it forces the caller to consider that there cannot be a returned value, and that this is a valid condition ... Consider the quotes from the answers linked above:

Missing a value is a more accurate statement than null

and

Any reader of your code or user of your API will be beaten on the head with the fact that there can be nothing there and that you must check before accessing the value.

So, when I see the signature of the return type Optional<Map<String, String>> , I think of it as a return type of function, where an empty Map may be a valid return value, but also the absence of a Map .

Examples of this include getCachedFavoriteColors , findInvalidValuePairs , etc. In the first case, there may not be any users who return an empty Map , but there cannot be a cache value that will return an invalid Optional . In the second case, there cannot be pairs of invalid values ​​that again return an empty Map , but also may not be an Invalidator . You get the idea.

Note that in some cases above, you can throw an exception instead of returning an invalid Optional . This is your decision as an API designer.

+9
source

All Articles