Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the real benefit of returning Optional<Map<String, String>> rather than just an empty Map<String, String> [duplicate]

If my code returns Map<String, String> for sure, but could be empty. Is there a benefit of converting it to return Optional<Map<String, String>>. Would it add any benefit to empty but not null instances?

like image 566
ssgao Avatar asked Apr 18 '15 01:04

ssgao


People also ask

Should you return optional Java?

An Optional type can be a return type for most methods except some scenarios discussed later in the tutorial. It's also appropriate for a static method or utility method to return an Optional value. However, there are many situations where we should not return an Optional type.

How to return empty Optional Java?

Programmers can also use the ofNullable() method, which will return an empty Optional object if the value is null, or an Optional object containing the given value if it is non-null. Finally, you can create an empty Optional object using the empty() method.

How can I return optional value in Java?

Optional<String> value = Optional. of(str[ 2 ]); // It returns value of an Optional.

How do you know if optional is not empty?

Solution: Using Optional Class ofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional. We can check whether the returned Optional value is empty or non-empty using the isPresent() method.


1 Answers

Like so many subjects in computer programming, It Depends (tm).

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

absence of a value is a more precise formulation than null

and

Any reader of your code or consumer of your API will be beaten over the head with the fact that there might be nothing there and that a check is necessary before accessing the value.

So when I see the return type signature Optional<Map<String, String>>, I think of it as a return type from a function where an empty Map might be a valid return value, but so is an entire lack of a Map.

Examples of this include getCachedFavoriteColors, findInvalidValuePairs, etc. In the former case, there might not be any any users, which would return an empty Map -- but there might not be a cache value, which would return an invalid Optional. In the second case, there might not be any invalid value pairs, which would again return an empty Map, but there also might not be an Invalidator. You get the idea.

Note that in some of the cases above you might want to throw an exception instead of return an invalid Optional. That's your decision as an API designer.

like image 160
George Hilliard Avatar answered Oct 16 '22 18:10

George Hilliard