Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 367
Alstresh Avatar asked Aug 31 '15 08:08

Alstresh


2 Answers

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"));
like image 141
Tagir Valeev Avatar answered Sep 28 '22 05:09

Tagir Valeev


//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.

like image 22
Marko Topolnik Avatar answered Sep 28 '22 05:09

Marko Topolnik