Saturday, March 12, 2011

Return 0 sized array rather than nulls

Using null return approach:
public String[] getStrings() {
if( foo ) {
return null;
} else {
return new String[] {"bar, "baz"};
}
}
//Now using this function
String[] strings = getStrings();if (strings != null) { for (String s : strings) { blah(s); }}

Using 0 sized array
public String[] getStrings() {
if( foo ) {
return new String[0];
} else {
return new String[] {"bar, "baz"};
}
}

//Now using the function above
// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
blah(s);
}
So its definitely worth using java feature of allowing 0 sized array.

No comments:

Post a Comment

Chitika