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.
source
share