1

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?

Community
  • 1
  • 1
gixlg
  • 1,193
  • 1
  • 9
  • 21
  • You can find the answer in the following question. [https://stackoverflow.com/questions/3458451/check-chains-of-get-calls-for-null](https://stackoverflow.com/questions/3458451/check-chains-of-get-calls-for-null) – LeoN Apr 02 '19 at 10:17

3 Answers3

7

Use Optional:

return Optional.ofNullable(someMethod())
    .map(Meeting::getRoom)
    .map(Room::getProjector)
    .map(Projector::getModelName)
    .orElse("No Projector Exist");

As an aside, consider returning Optional or null from your method - having to compare your String to the special hardcoded value to detect the null case is going to get tiresome...

Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

Checking all the null conditions in one if statement also can be done as follows. So that the code will be much easier to read.

    if (meeting != null && meeting.getRoom() != null && meeting.getRoom().getProjector() != null) {
        return meeting.getRoom().getProjector().getModelName();
    } else {
        return "No Projector Exist";
    }

The best way is to move the null checks to a private method. So when you give a meeting object, it do the required checks and return the model of the project as a string. So your code will be much simpler and with less complex.

LeoN
  • 1,590
  • 1
  • 11
  • 19
-3

You can catch() the NullPointerException or throw a NoRoomException and a NoProjectorException from your getRoom() and getProjector() methods and catch those.