String s = foo.getBar().getFrobz().getNobz().getBaz();
I want to return the value getBaz(). The problem is that any of the other methods can return null- in this case, I just want to return an empty string.
Here is one way to achieve this effect:
String s = "";
if (foo.getBar() != null ) {
if (foo.getBar().getFrobz() != null) {
if (foo.getBar().getFrobz().getNobz() != null) {
if (foo.getBar().getFrobz().getNobz().getBaz() != null) {
s = foo.getBar().getFrobz().getNobz().getBaz();
}
}
}
}
And here is another simple way:
String s = "";
try {
s = foo.getBar().getFrobz().getNobz().getBaz();
} catch (NullPointerException npe) {
}
I heard that exceptions are more expensive than statements, but they looked cleaner. Maybe this issue can be solved differently? Any help is appreciated.
source
share