Monday, July 22, 2013

A simple way to avoid a lot of null pointers

This is something I see all the time and a slight code change can remove a lot of null pointer exceptions.

public class NullExample {

 private static final Integer ZERO = 0;
 
 public static void main(String args[]) {
  
  //Bad Way
  System.out.println("1 -> " + checkEqualToZeroPoor(1));
  System.out.println("0 -> " + checkEqualToZeroPoor(0));
  try {
   checkEqualToZeroPoor(null);
  } catch(NullPointerException e) {
   System.out.println("Null throws an exception");
  }
  
  // Good Way
  System.out.println("1 -> " + checkEqualToZeroGood(1));
  System.out.println("0 -> " + checkEqualToZeroGood(0));
  try {
   System.out.println("Null -> " + checkEqualToZeroGood(null));
  } catch(NullPointerException e) {
   System.out.println("This should never be reached");
  }
 }
 
 public static boolean checkEqualToZeroPoor(Integer value) {
  // A null pointer exception will be thrown
  return value.equals(ZERO);
 }
 
 public static boolean checkEqualToZeroGood(Integer value) {
  // Should return false on null
  return ZERO.equals(value);
 }
}

In the 'poor' example, the parameter's .equals method is being used to check equality with our static value. By switching these two we can ensure that the object on which the .equals method is always initialized and never null.

Granted, this example ignores the third case, which gives the same result as the better method but is not advisable.


// Worse way
System.out.println("1 -> " + (1 == ZERO));
System.out.println("0 -> " + (0 == ZERO));
System.out.println("null -> " + (null == ZERO));

While this might seem incredibly basic, it still happens on a daily basis




1 comment:

Fabien Taysse said...

Well, this is just "Yoda condition" :)
http://www.dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html

Quite a handy tip for those who never used it anyway :)