27 April, 2012

Avoid Null Pointer Exception Part 1


Null Pointer Exception is the most common and most annoying exception in Java.
In this post I want to avoid this undesired exception.

First let's create example that raise Null Pointer Exception
   private Boolean isFinished(String status) {  
     if (status.equalsIgnoreCase("Finish")) {  
       return Boolean.TRUE;  
     } else {  
       return Boolean.FALSE;  
     }  
   }  

In previous method if we pass the value of "status" variable as null it will raise Null Pointer Exception in below line
if (status.equalsIgnoreCase("Finish")) {



So we should change my code to below code to avoid Null Pointer Exception
    private Boolean isFinished(String status) {
        if ("Finish".equalsIgnoreCase(status)) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

In previous method if we path the value of "status" variable as null it will not raise Null Pointer Exception.

Conclusion
If you have object.equals(”literal”) you should replace with “literal”.equals(object) .

If you have object.equals(Enum.enumElement) you should replace with Enum.enumElement.equals(object).

At general expose equals method of the object that you are sure that it doesn't has null value.

Thanks

12 comments:

  1. Good suggestion.One of my colleagues suggested this trick to me and I have been able to avoid the null pointers occurring due to object.equals("String") especially when the value of object is not in your control.

    ReplyDelete
  2. Avoiding NPEs is good, but if null is not a valid input for this function, the solution presented is just hiding another error. You could add an assert for testing and/or throw an IllegalArgumentException for unexpected input.

    My personal tip for avoiding NPEs is to never intentionally return null from a function. I.e. don't use null as a synonym for "no result" or "false."

    ReplyDelete
    Replies
    1. Avoiding NPE doesn't mean that return null of function but I present best practice of how prevent your code not throw NPE and I am agree with you to Asset and/or throw exception because of null value

      Delete
  3. I think that this masking the null object. I completely agree with the above comment. I do this on a regular basis:

    For example:

    Assert.notNull(status);

    ReplyDelete
    Replies
    1. I am also agree with you to assert but what I present is to avoid my code itself to throw NPE
      But if business utself throw NPE I should assert and/or throw exception

      Delete
    2. It is a well known "trick" to avoid NPE. In this case a null value for status is allowed and the method simply would return false. I think the tilte of the post should be "avoiding null check", since another implementation could be

      if (status == null) return false;
      return status.equalsIgnoreCase("Finish");

      For the sake of shortness I would prefer the one liner implementation:
      return "Finish".equalsIgnoreCase(status);

      but that's another topic

      Delete
    3. This comment has been removed by the author.

      Delete
  4. agreed with the two ano's above. In addition, if you do it don't code it yourself but use StringUtils from apache commons-lang3.

    org.apache.commons.StringUtils.equals(..,..);

    ReplyDelete
  5. Funny, I just today suggested that we switch back from our recommendation of using CONSTANT.equals(value) to value.equals(CONSTANT) as others mentioned as well null is a "bad citizen" in Java. Like one of my former colleagues put it:
    "null may be used for everything and is useful for nothing" :-)

    ReplyDelete
  6. We use StringUtils.equals for all string comparisons in order to avoid null pointer exceptions.

    We return an instance of Optional (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html) from methods where nothing could be returned e.g. find(final long id) in a DAO.

    ReplyDelete
    Replies
    1. Ok I will write about org.apache.commons.lang.StringUtils class in the next post (second part)

      Delete
  7. I posted Part2 related to this post also
    http://mahmoudoracle.blogspot.com/2012/05/acoid-null-pointer-exception-part-2.html

    ReplyDelete

How to Pass Parameters to ActionListener in ADF

In some cases, it is required to pass a value to ActionListener of ADF Button. The method that can be invoked by actionListeners has only...