Home > Software design >  Why do we need to check if an object is null?
Why do we need to check if an object is null?

Time:05-21

Suppose I have a piece of code in the program:

MyMessage message = getMessage(id); // call getMessage to return a message object
message.getUserId();

Someone suggests that I should check null of the message before calling message.getUserId().

There are two ways to check null: 1st:

MyMessage message = getMessage(id); // call getMessage to return a message object
if(message == null) {
   LOGGER.Error("message is null");
   return;
}
message.getUserId();

2nd way:

MyMessage message = getMessage(id); // call getMessage to return a message object
if(message == null) {
   throw NullPointerException;
}
message.getUserId();

My question is:

  1. which way is better for null checking? return or throw exception?
  2. Why do we need null check here? If we don't, then message.getUserId();will throw NullPointerExceptionanyway.

CodePudding user response:

It is always best to handle all exceptions. It isn't particularly pleasant for the user to see the exception (with all the stack trace it outputs). Displaying a clear message in an appropriate way and explicitly checking for any cases which might lead to an exception is the way to go. However, there is one exception (pun intended): when calling the method from another one and you need to particularly know what went wrong - then it is better to throw an exception of the appropriate type with a proper message instead of returning strings and doing other shenanigans.

To directly answer your questions:

  1. The first way (clear message displayed in an appropriate way, checking explicitly for cases that may lead to an exception) is better if the code is intended to display directly data to the user. However, the second way (throwing exceptions) is better if the data is to be used by computers.

  2. Because otherwise those that are reading your code might not think that the message can be null. Additionally, this would not require exception handling and so nobody can know that this method can throw the exception. However, when you explicitly check for null and throw the error explicitly, this would require adding the "throws" keyword to the method signature, which would require NullPointerException handling by whatever calls that method.

CodePudding user response:

This depends on what you want. However, something is clean and clear: we definitely do not want unhandled runtime exceptions.

One way is check your object if null and create an custom exception for your business then catch this exception to either do your business or inform your client

public void yourMethod(){
    ...
    if(object == null){
      throw new CustomBusinessException("Object is null", object)
    }
    ...
 }
 
public void yourFirstCallMethod(){
    ...
    try{
        yourMethod()
    }catch(CustomBusinessException e){
        // do your business or inform client
    }
    ...
}

in this logic you can detailed your exceptions and do not lose other exceptions like following:

   try{
       yourMethod()
   }catch(CustomBusinessException e){
       // do your business or inform client
   }catch(CustomOtherBusinessException e){
       // do your business or inform client
   }catch(CustomAnotherBusinessException e){
       // do your business or inform client
   }catch(RuntimeException e){
       // if you really want to catch default exceptions, and make some different business to do.
   }catch(Exception e){
       // if you really want to catch all other exceptions.
   }

As i said there is no "true" or "strict" way to do this. However, in my opinion this is good way to seperate your exceptions.

  • Related