vendredi 5 août 2016

Efficient null check for a compound object in Java

There is a bundle.category.subcategory.item that I want keep on refresh. Refresh is called at different stages. As a result bundle might be null. Or bundle might be constructed, but bundle.category remains null, etc.

A check for if(bundle.category.subcategory.item!=null) results in exception if bundle==null. I can write something bulky:

if(bundle!=null &&
     bundle.category!=null &&
     bundle.category.subcategory!=null &&     
     bundle.category.subcategory.item!=null){

     myItem = bundle.category.subcategory.item
}

But it doesn't scale well. Is there a better way to do this null check?

Aucun commentaire:

Enregistrer un commentaire