1. Overview
Optional is a great way to make sure whether the result is present. This article primarily discusses one anti-patterns of Optional.
There are several ways to extract value, if present, from an Optional. But using a combination of isPresent() and get() methods to extract value leads to code pollution.
This article is part of an ongoing series of Optional. Read about it more here.
2. isPresent() and get()
Optional class provides a get() method which returns the value, if present. If value is not present, then get() method throws NullPointerException.
So in order to use get() we need to prove that value exists in Optional. Unfortunately, this leads to testability using isPresent().
If we want to avoid NullPointerException, we do so by checking if we are trying to dereference a null pointer.
String result = "result"; if (result != null) { // do something with result }
Using Optional we can achieve essentially the same thing using isPresent() and get() method.
Optional<String> optResult = ...; //Some optional. if (optResult.isPresent()) { String res = optResult.get(); // do something with result }
3. Comparison
Null comparison makes an explicit check for nulls. We have done this time and again. We know why we write this code and we know what is the intent of this code.
If using Optional, we are using two methods calls essentially to achieve the same result as of null comparison. Combination of isPresent() and get() is just a clutter and must be avoided.
Read the stackoverflow discussion by Brain Goetz here. Do read the comments of the answer too.
4. Conclusion
Using Optional just to check for nulls is not a good way to use Optional. We may end up writing a lot of if-else conditions which will end up increasing the complexity of code. If you think you will just end up using isPresent() and get() method then it Optional is not the right use-case for you.