I am working on sprint boot application, and I am working on SonarQube blocker resolving an issue.
So I get one issue to be resolved:
Ensure this "Optional" could never be null and remove this null-check.
So I have changed the condition from
myObj != null -> Optional.ofNullable(myObj).isPresent()
I can't use myObj.isPresent()
directly as myObj
can be null
, so it will throw null pointers.
Now I'm stacked in one situation when myObj
is empty as
myObj= Optional.empty();
Optional.ofNullable(myObj).isPresent(); // True
myObj.isPresent(); // False;
So as I have mentioned I have changed my condition checking myObj!=null
with Optional.ofNullable(myObj).isPresent()
, it will work fine for null
object and if object is empty then it will be true for empty object and when I access get()
on object then it'll throw : No value present
How can I avoid null
and empty together in one condition?
I don't want to add && condition to check for non-empty of myObj as :
Optional.ofNullable(myObj).isPresent() && !myObj.isEmpty()
Can I check this with single statement for null as well for empty or vice-versa?