Skip to main content

Method return values for null objects

Posted by staufferjames on July 31, 2007 at 6:04 AM PDT

Would it be useful to be able to provide method return values for null objects?
For the List interface, the null return values might include:

get(int) : null

size() : 0

iterator() : An empty iterator

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

List items = null;

if(false) {
  items = ...
}

for(int index = 0; index < items.size(); index++) {//Since items is null, the value 0 is used as defined above.
  Object obj = items.get(index);
}

Another example for a class called Person:

getName : null

getAge() : -1



Person person = null;

if(false) {
  person = ...
}

if(person.getAge() > 18) {
  //allow to vote (18 is the voting age in the U.S.A.)
}

It allow you to resonably ignore nulls when desired but still always have the opportunity to check them. This wouldn't be something that is always required but could be optionally set in the class or interface.

Note: It probably wouldn't be a good idea to do this to any class or interface in the Java core just because it would change how programs run but it would be useful if I could do this on new classes or interfaces that I make. I am also not suggesting the way the programmer would write the defaults so ignore the exact syntax that I used.

Related Topics >>