0

I'm trying to avoid the traditional if / else block by using Java Optional. But I still missing the understanding of how to implement the next requirement :

    if (x != null)
       foo1();
    else
       foo2();

public void foo1(){
   print("X not null");
}

public void foo2(){
   print("X is null");
}

thanks

Igal
  • 4,603
  • 14
  • 41
  • 66

2 Answers2

8

From jdk-9 you can use ifPresentOrElse

public void ifPresentOrElse​(Consumer<? super T> action,
                        Runnable emptyAction)

Code

Optional.ofNullable(x).ifPresentOrElse(x->foo1(), ()->foo2());
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
2

I'm trying to avoid the traditional if / else block

That's the problem. There is no reason to rewrite the snippet you provided to Optional. You won't benefit from it in any way.

if-else is a control flow statement, while Optional is an util that indicates the absence of a return value with a bunch of functional-like methods to handle it nicely.

If you are looking for a shortcut, or a more precise way to express it, go with a ternary operator.

print(x != null ? "X not null" : "X is null");

Otherwise, leave it as it is. You can always find something more interesting to play around with.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Can you perhaps explain how *avoiding the traditional `if/else` block* **is the problem**? The fact that "there's no reason to do it" doesn't necessarily make it *the problem*... Also, it's interesting that the conditional operator is suggested as a better alternative for getting rid of the `if/else` block. – ernest_k Jul 29 '19 at 12:26
  • but note with the void functions (which one might want to call), you cannot (At least I could not, maybe you have an idea, I got stuck) get the ternary operarator to do the trick unless you convert them to something that returns a meaningless value, like a boolean of true, that you then ignore. – Jeremy Kahan Jul 29 '19 at 12:26
  • @ernest_k Personally speaking, thinking about rewriting a harmless `if-else` to an unjustified `Optional` is a problem... – Andrew Tobilko Jul 29 '19 at 12:32
  • 1
    @JeremyKahan the methods may return `String` which would be the value to print: it wouldn't be *that* meaningless... The example looks rather superficial, though. So there is little to talk about... – Andrew Tobilko Jul 29 '19 at 12:37
  • @AndrewTobilko yeah, that's a good point. It's consistent with the design principles I have been reading about that output is a side effect, and you don't want your lower level functions to have them. – Jeremy Kahan Jul 29 '19 at 12:44