Handle Chained Method Calls avoiding NullPointerException - Which is the best way?
Let's imagine this kind of scenario:
3 class Meeting
, Room
, Projector
A Meeting might have set a Room and it might have a Projector inside them.
Now suppose that I want to know what is the model of the Projector. The most natural thing is to do something like
Meeting meeting = someMethod();
return meeting.getRoom().getProjector().getModelName();
This code could return the model name of the Projector correctly,
unfortunately this code could also cause an Exeption: an java.lang.NullPointerException
in case that one of the class contained into the root class Meeting (or even the Meeting class) is null.
In order to prevent this problem, and get a default value in the worst case we should check the returned value of each call.
Meeting meeting = someMethod();
if (meeting != null) {
Room room = meeting.getRoom();
if (room != null) {
Projector projector = room.getProjector();
if (projector != null) {
return projector.getModelName;
}
}
}
return "No Projector Exist";
The code now is pretty nasty.
What is the best way to deal with this kind of chained method calls avoiding the NullPointerException?