My thoughts as an enterprise Java developer.

Monday, May 07, 2007

Method return values for null objects

Would it be useful to be able to provide method return value for null objects?
For a List the null return values might be:
get(int) : null
size() : 0
iterator() would be an empty iterator

That would allow the following code that has less null checks.

List items = null;

if(something) {
items = ...
}

for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}

2 comments:

Anonymous said...

I think if you do that you break what null is really meant to represent (i.e. a pointer with a reference to nothing), I often use the following idiom though:

final List items = new MyListImplementation();

if(something) {
items.addAll(otherThing);
}

for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}

James A. N. Stauffer said...

You could still check for null and the defaults would only be set when explicitly set by the class/interface of the variable type. I just think there are times when I want to ignore nulls.