Core Java

Optional in collections

Sometime it is argued that the type Optional is worth being used in collections. It allegedly solves the problem of e.g.: HashMap that returns null in case there is no mapping for a key as well as when the value null is mapped to the key. If you use a Map<Optional<Something>> then you can clearly separate a missing mapping and an absent value. And that way you are one level deeper in the rabbit hole.

First of all:

you can

tell if a key is mapped to null or not mapped without using Optional. There is the method containsKey(). This is one more method call to separate the non-mapped key from a mapped null value. However calling the methods of Optional is also. So what is the point? On the other hand

you do not need

to tell if the key is mapped to null or the mapping is missing. If there is a difference in your program code between the two cases then you created the code for the business login in a wrong way. This is certainly code smell. Think of null as “nothing”, and instead of thinking “null is assigned to the key ‘aaaaaarrghhh’” say out loud: Nothing is assigned to the key ‘aaaaaarrghhh’. You see? There is no difference except that all look at you now in the office.

And using optional as a value in a Map

you will

end up one level deeper in the rabbit hole after a while. Code lives independent life. It is not only you, who develop it. In large organizations there are developers who are certainly drunk when code. (This is the only reasonable explanation for some code.) They will soon populate your Map<Optional<Something>> with

  • null values,
  • absent Optional values
  • and even with Optional object that wrap something else but not your “Something“.

From time to time, if you are lucky you may even find some non null, non absent Optional<Something> values.

Reference: Optional in collections from our JCG partner Peter Verhas at the Java Deep blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button