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?