Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace my old Java code with Optionals (Functional programming)?

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?

like image 431
0seNse0 Avatar asked Sep 25 '26 19:09

0seNse0


2 Answers

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());
like image 193
Smutje Avatar answered Sep 27 '26 08:09

Smutje


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.

like image 33
daniu Avatar answered Sep 27 '26 08:09

daniu