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
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 getB() {
return Optional.ofNullable(b);
}
}
class SubObject {
private SubObject2 c;
Optional 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.