Thursday, 2 September 2010

NullPointerException - Most Common Java Bug In Existence

Unless you are what is called "the Perfect Java Programmer", it is likely that you've perpetrated the NullPointerException at least once (and probably a lot more) in your life.

A lot of the time, I see code like the following:
if (propertyValue.equals("filename.txt"))
{
    // do stuff
}
When it should really be more like this:
if ("filename.txt".equals(propertyValue))
{
    // do stuff
}

Now, as you can see when you try this (with propertyValue = null;), a NullPointerException does not take place.

The reason is in the equals method. Contract states that x.equals(null) == false.

If you're new at Java, you might be rather surprised that something like "somestring".equals() works. Remember that Strings are immutable objects, and therefore there's really no reason not to try something like this.

With that said, let's try and find a common implementation for the equals method. Eclipse seems to do a pretty good job of it:

public class MyObject
{

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            // it is the same object
            return true;
        }
        if (obj == null)
        {
            // oh dear
            return false;
        }
        if (getClass() != obj.getClass())
        {
            // not the same class
            return false;
        }
        MyObject other = (myObject) obj;
        if (!this.field().equals(obj.field())
        {
            // (one of) the fields is not the same!
            return false;
        }
        // couldn't find any differences!
        return true;
    }

    @Override
    public int hashCode() 
    {
        return field();
    }

}
The link to http://community.jboss.org/wiki/EqualsandHashCode might be a good one.

No comments:

Post a Comment