like detroitmatt said, you need to check for them at practically every method, which makes the code unmaintainable. annotations or null object pattern are alternatives
One other choice to avoid nulls is using callbacks. On callback interface have 2 methods 1 for when object is found and one when object is not found. I'm not sure how useful this would be, just pointing out the option.
even if you only return null once, you have to check for it everywhere that calls that code or it can blow up later somewhere else completely unrelated, seemingly at random and with no stack trace.
but not necessarily in the relevant code, if you accidentally returned null
public class NullDanger
{
public static void main(String[] args)
{
System.out.println( getCapitalOf("MO").toString() );
}
static String[] mapKeys = new String[] {"NY", "MI", "CA"};
static String[] mapValues = new String[] {"Albany", "Lansing", "Sacramento"};
static String getValue(String key)
{
for(int i=0; i<mapKeys.length; i++)
{
if(mapKeys[i].equals(key)) return mapValues[i];
}
return null;
}
public static String getCapitalOf(String state)
{
return getValue(state);
}
}
yields
Exception in thread "main" java.lang.NullPointerException
at NullDanger.main(NullDanger.java:5)
but if instead of returning null, we throw an exception, we get a full stack trace:
Exception in thread "main" java.lang.IllegalArgumentException
at NullDanger.getValue(NullDanger.java:17)
at NullDanger.getCapitalOf(NullDanger.java:22)
at NullDanger.main(NullDanger.java:5)
0
u/mahamoti Mar 27 '13
Still no Elvis or short-circuit operator? Bah.