Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid checking null value of intermediates objects

Tags:

java

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 ?

like image 936
Seb Avatar asked Jan 29 '20 15:01

Seb


2 Answers

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.

like image 84
Iskuskov Alexander Avatar answered Oct 20 '22 16:10

Iskuskov Alexander


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.

like image 24
AstarAndy Avatar answered Oct 20 '22 16:10

AstarAndy