We have all seen that kind of code
if (myObject!= null
&& myObject.mySubObject() != null
&& myObject.mySubObject().getSpecificValue() != null
&& !myObject.mySubObject().getSpecificValue().isEmpty()
) {
......
}
How could I write this the clean way ?
You can do chaining with Optional
:
Optional.ofNullable(myObject)
.map(o -> o.mySubObject())
.map(so -> so.getSpecificValue())
.map(sv -> sv.isEmpty())
.orElse(false)
Or with method references even shorter (does the same):
Optional.ofNullable(myObject)
.map(Foo::mySubObject)
.map(Bar::getSpecificValue)
.map(Baz::isEmpty)
.orElse(false)
where Foo
, Bar
and Baz
are the names of the respective classes.
If you are using someone else's code then you're really stuck handling for a possible null
. On the other hand, if you have control over the code base then never return a null
object, and make that a rule across your entire application.
This may sound bad at first but I have developed several enterprise-level applications and this is a very effective way to make the code consistent and much more readable.
So, now, this
if (myString != null && !myString.isEmpty()) {
becomes simply
if (!myString.isEmpty()) {
In lue of that option use the new Optional
feature in J8 as it is intended for that purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With