mercredi 23 décembre 2015

Optional in Java8 as a way to completely reduce if statements

I think that about 90% of articles about Optional type in Java 8 are about the topic how Optional helps to remove nulls from your code. Like for instance in this simple example:

Optional.ofNullable(foo).orElse(defaultFoo);

But Optional can also be amazingly useful when it comes to removing not only null checks from your code but also if else statements, by simulating something like 'pattern matching'. Let's see at this simple example:

Assume I have the following logic:

List<Foo> foos = barSrv.getFoos(); // assume never null
if (foos.size() == 1) { return foos.get(0); } else { return barSthElse()};

what can be rewritten in this way:

return Optional.of(barSrv.getFoos()).filter(l -> l.size() ==1).map(l -> l.stream().findFirst().get()).orElse(() -> barSthElse());

Question: Is there any 'official' recomendation to use Optional in this way or it was introduced to avoid nulls only.

Aucun commentaire:

Enregistrer un commentaire