Sometimes I face I must write a piece of code like this (usually it have more nested if and more complex structure but for the example is enought)
public voi
A code should never include exception handlers for unchecked exceptions. A null check should always be used for an object reference which has a chance of being null.
If you migrate to Java 8 you can use Optional and Lambdas. First, you need to rewrite your classes to return Optional
of each type:
class Object1 {
private SubObject b;
Optional<SubObject> getB() {
return Optional.ofNullable(b);
}
}
class SubObject {
private SubObject2 c;
Optional<SubObject2> getC() {
return Optional.ofNullable(c);
}
}
class SubObject2 {
@Override
public String toString() {
return "to be printed";
}
}
Now, you can chain the calls without the risk of NullPointerExceptions in a concise way:
a.getB()
.flatMap(SubObject::getC)
.ifPresent(System.out::println);
See the Oracle's article Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! for more information.
The wrongest part of the second version is that when a NPE happens inside the getB()
, getC()
it will be silently ignored. As already mentioned, exceptions are for exceptional cases.
Using Java 8 optional:
Optional.ofNullable(a)
.map(Object1::getB)
.map(SubObject::getC)
.ifPresent(Object2::print);