Consider the usage of this expression:
String hi = Optional.ofNullable(sayHi()).orElse(\"-\");
which effectively corresponds to this ternar
Is this usage of
Optional.ofNullablewith a method call a good practice?
Conceptually, it's a bad practice. The basic idea is to represent the absence of a return value, not to wrap everything that might be null. I am strongly against this usage.
Or just extra verbose coding?
It looks to me like a failed attempt to make your code more fashionable. ("Look, we are using brand-new Optional from Java 8!")
I prefer readability and clarity over conciseness.
This Optinal usage doesn't provide clarity but raises questions:
Why do you wrap the variable?
What are you going to do with this Optional?
Will it be used/returned below?
It doesn't give brevity either: your second line is even shorter.
To avoid this problem you actually could create an extra variable but this adds to the verbosity of the ternary option.
You aren't creating an extra variable. The one-line version could be:
String hi = (hi = sayHi()) != null ? hi : "-";
Though, your two-line suggestion is absolutely fine:
String messageContent = sayHi();
String hi = messageContent != null ? messageContent : "-";