Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing OR with multiple conditions using Optional wrapper

I am trying to understand and use Java 8 - Optional feature. I would like to refactor this code block. Without Optional I have such a condition.

ClassA objA = findObject();
if(objA == null || objA.isDeleted()){
  throw Exception("Object is not found.");
}

I want to transform this block using Optional wrapper. I have read about filter, ifPresent functions but I could not find a way. Maybe it is simple but I am new to Java 8. I would appreciate if you could help.

like image 587
Eric Avatar asked Dec 17 '22 23:12

Eric


1 Answers

You shouldn't use Optional<T> to solely replace the if statement as it's no better and doesn't gain you any benefit. A much better solution would be to make the findObject() method return Optional<ClassA>.

This makes the caller of this method decide what to do in the "no value" case.

Assuming you've made this change, you can then leverage the Optional<T> type:

findObject().filter(a -> !a.isDeleted())  // if not deleted then do something 
            .map(...)  // do some mapping maybe?
            ...  // do some additional logic
            .orElseThrow(() -> new Exception("Object is not found."));//if object not found then throw exception

see the Optional<T> class to familiarise your self with the API and the methods that are available.

like image 77
Ousmane D. Avatar answered Jan 25 '23 22:01

Ousmane D.