Reputation: 43
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?
Upvotes: 3
Views: 138
Reputation: 18163
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());
Upvotes: 3
Reputation: 35467
First, make your methods dbService.findByA
and dbService.findByB
return Optional
. That's the basis. If you don't do that, you don't do "functional" programming.
Second, use Java 9+ (or better, the latest version).
Then simply use the following:
ClassA instance = dbService.findByA(a)
.or(() -> dbService.findByB(b))
.orElseThrow(Exception::new);
If you're stuck with Java 8, do the following:
ClassA instance = Optional.of(() -> dbService.findByA(a)) // Optional<Optional<ClassA>>
.orElseGet(() -> dbService.findByB(b)) // Optional<ClassA>
.orElseThrow(Exception::new);
Upvotes: 1
Reputation: 15008
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.
Upvotes: 2