简体   繁体   中英

Would it be useful to have 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() : 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);
}

This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.

From: http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html

It is nice to not have to check for NULL, and some languages make it easier -- eg C#'s non-NULLable types, or Haskell which doesn't have NULLs but can express a missing value with the Maybe type constructor.

A NULL is distinct from an empty list. You can take the point-of-view that someone passing in a NULL where you need a list is making a programming error, and that the right thing to do is throw a NullPointerException.

The typical excuse for accepting NULLs is that often there's a case where you don't need the list, and you shouldn't have to create a new List that's empty, especially when there's some concern about efficiency. You can have many of the benefits without changing the language, but by instead having a static EmptyList that people can pass in, that never needs to be reinitialized.

It's a pattern called Null Object

http://en.wikipedia.org/wiki/Null_Object_pattern

This is a good idea.

Smalltalk does this.

There is a NULL object. It doesn't descend from Object. (Smalltalk is a singly-rooted class hierarchy like Java)

For the advanced student, you can sub-class it for making proxies!

Ruby does this (as well as others). It has nil instead of null and it's an object.

I dp hate when functions that are meant to return lists can return null. It's better to return an empty list and let the user decide if they want to check for null (empty) or not.

In C# (among other languages), this is normally not allowed. Without an instance of Foo, .net doesn't know to call Foo's method or Foo's child's method.

However, an C# 3.0 extension method applied to the Foo type would allow this:

Foo x = null;
if (x.Bar() == 0)
{
  Console.WriteLine("I win");
}

Bar could be constructed like so:

public static int Bar (this Foo theFoo)
{
  return theFoo == null ? 0 : 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM