How do you simulate a null safe statement with a default return value?

I apologize for the title, but I cannot find a good way to describe the problem in one sentence. In short, I have a lot of Java code following this pattern

if (obj != null && obj.getPropertyX() != null) {
    return obj.getPropertyX();
}
return defaultProperty;

which can be rewritten as

return obj != null && obj.getPropertyX() != null ? obj.getPropertyX() : defaultProperty;

This is still ugly, and I am wondering if there is any API in Google Guava or another library to help clear this code. In particular, I'm looking for something like

return someAPI(obj, "getPropertyX", defaultProperty);

I can implement this method using reflection, but I'm not sure if this is the right way to do this. Thanks.

+4
source share
1 answer

In Java 8, you can use:

return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);
+6
source

Source: https://habr.com/ru/post/1613571/


All Articles