Avoiding null pointer exceptions

posted 29 Dec 2010, 05:49 by Sanjeev Kumar   [ updated 17 Nov 2011, 09:10 ]
Null pointer exceptions(NPE) are the undoubtedly the most common and most annoying errors. In most cases I have observed that it could have been avoided by simply sticking to some best coding practices while writing code. Here is an example of a potential NPE.

    // BAD CODE
    private Boolean isExpired(final StatusEnum status) {
        if (status.equals(StatusEnum.EXPIRED)) { // Potential null pointer if status is null.
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

Here if the "status" that is passed to the method is null you will get a NPE at the first statement in the method. However if we write the code like as follows it can be avoided.

    //GOOD CODE
    private Boolean isExpired(final StatusEnum status) {
        if (StatusEnum.EXPIRED.equals(status)) { // Move variable part as parameter to equals method.
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

Some editors like IntelliJ provide a quick fix for similar use cases. If you have object.equals(”string literal”) it can replace with “string literal”.equals(object)  and you can do the replace all on your entire code base in one go if you wish. 

Happy coding!!

Comments