How to replace the below code using Java 8 Optionals (Functional programming)?
ClassA classA = dbService.findByA(a);
if (classA == null) {
classA = dbService.findByB(b);
}
if (classA == null) {
throw new Exception();
}
return classA;
edit:
Maybe if I will make findByA and findByB returning Optional will make my code cleaner using Functional programming?
return Optional.ofNullable(Optional.ofNullable(dbService.findByA(a))
.orElseGet(() -> dbService.findByB(b)))
.orElseThrow(() -> new Exception());
Or, Java 9, a bit nicer:
Optional.ofNullable(dbService.findByA(a))
.or(() -> Optional.ofNullable(dbService.findByB(b)))
.orElseThrow(() -> new Exception());
This would work
Optional.ofNullable(
Optional.ofNullable(dbService.findByA(a))
.orElseGet(() -> dbService.findByB(b))
).orElseThrow(Exception::new);
I don't think this is much nicer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With