Alstresh
Alstresh

Reputation: 583

If not null - java 8 style

Java 8 presents Optional class.

Before (Java 7):

Order order = orderBean.getOrder(id);
if (order != null) {
    order.setStatus(true);
    pm.persist(order);
} else {
    logger.warning("Order is null");
}

So on Java 8 style:

Optional<Order> optional = Optional.ofNullable(orderBean.getOrder(id));
optional.ifPresent( s -> {
    s.setStatus(true);
    pm.persist(s);
    //Can we return from method in this place (not from lambda) ???
});
//So if return take place above, we can avoid if (!optional.isPresent) check
if (!optional.isPresent) {
    logger.warning("Order is null");
} 

Is it correct to use Optional in this case? Can anyone propose a more convenient way in Java 8 style?

Upvotes: 14

Views: 12922

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200158

//Can we return from method in this plase (not from lambda) ???

Lambdas do not implement "non-local return" semantics, therefore the answer is no.

Generally, since you need side-effectful action in both the case where the value is present and not, a branching point in the code is essential—whether you wrap it in some fancy API or not. Also, FP generally helps improve referentially transparent transformations (i.e., code built around pure functions) and not side effects, so you won't find much benefit by going through the Optional API.

Upvotes: 1

Tagir Valeev
Tagir Valeev

Reputation: 100209

Unfortunately, the ifPresentOrElse method you're looking for will be added only in JDK-9. Currently you can write your own static method in your project:

public static <T> void ifPresentOrElse(Optional<T> optional,
        Consumer<? super T> action, Runnable emptyAction) {
    if (optional.isPresent()) {
        action.accept(optional.get());
    } else {
        emptyAction.run();
    }
}

And use like this:

Optional<Order> optional = Optional.ofNullable(orderBean.getOrder(id));
ifPresentOrElse(optional, s -> {
    s.setStatus(true);
    pm.persist(s);
}, () -> logger.warning("Order is null"));

In Java-9 it would be easier:

optional.ifPresentOrElse(s -> {
    s.setStatus(true);
    pm.persist(s);
}, () -> logger.warning("Order is null"));

Upvotes: 12

Related Questions