Joe Joe - 1 year ago 62
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


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
is null, I'll have to call
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 Source

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)

if (optionalCategoryName.isPresent()) {
    System.out.println("Category Name is present and is " + optionalCategoryName.get());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download