Joe Joe - 12 days ago 4
Java Question

How to write null checks efficiently without calling the previous getter?

Assume I've a class Order, which contains an Object Item, which in turn Contains an Object Category, which again Contains a String

CategoryName
.

Now, I want to extract the category name from these nested objects only if none of these intermediate objects are null.

class Order {
Item item;
public Item getItem() {
return item;
}
}
class Item {
Category category;
public Category getCategory() {
return category;
}
}
class Category {
String categoryName;
public String getCategoryName() {
return categoryName;
}
}


The code I usually end up writing is:

if (order != null && order.getItem() != null && order.getItem().getCategory() != null
&& order.getItem().getCategory().getCategoryName() != null) {
System.out.println("Category Name is present and is " + order.getItem().getCategory().getCategoryName());
}


Is there a better way of checking this, instead of calling each of the getters again.
Like to check if
getCategoryName()
is null, I'll have to call
getItem().getCategory()
so I'm ending up calling these previous getters a lot of times when multiple objects are involved.


Another way is to create a variable of item after its null check, then create a variable of category and so on.

But is there a better way?

Answer

Note : This works from Java 8 and for before I guess Guava Optional should work in similar fashion.

Try using Optional.ofNullable

You can use map and nest the sub-objects there by eliminating the need to call those previous getters again. It also makes your code look more readable.

Optional<String> optionalCategoryName = Optional.ofNullable(order).map(Order::getItem)
        .map(Item::getCategory).map(Category::getCategoryName);

if (optionalCategoryName.isPresent()) {
    System.out.println("Category Name is present and is " + optionalCategoryName.get());
}
Comments