7 Replies - 9078 Views - Last Post: 12 June 2012 - 05:38 PM

#1 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Return Null or Return Empty

Posted 06 June 2012 - 08:31 PM

This might sound noobish to most of you, but what do you prefer, return a null or an empty instance of an object?
Well, I'm working on this tool that will generate something and send emails, and I made getters which will return an instance of the object InternetAddress. Now, the IDE told me I should either throw some exceptions or use a try - catch.

I tried the first, and all the methods where I invoked that class with the InternetAddress object I have to throw the same exceptions all over again. Now this is useful if the error found its way and the stack trace would really be traceable, but I feel what I'm doing with that is dirty.

So I tried the try - catch method and lo, the method now asks for a return object(seeing that the my return statement is wrapped in the try block). Eclipse then auto - generated a return null statement. Now, I'm pretty sure if I code correctly my program would never reach that line, but just to be sure I surfed a bit on the net and found out that an alternative is you could return an empty object.

Well, returning null or empty seems good to me, if you handle your code correctly, but I would like to hear your opinions on this. Should I just let the throws propagate through my program? Return a null? Return something empty?

Is This A Good Question/Topic? 0
  • +

Replies To: Return Null or Return Empty

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1152
  • View blog
  • Posts: 2,530
  • Joined: 05-May 05

Re: Return Null or Return Empty

Posted 06 June 2012 - 08:41 PM

I'd advise against returning an empty object in almost any case. By not returning null, you'll probably misled the API client into thinking the call was successful. You have to code defensively, taking in account the client may not read the docs or check for success.

This post has been edited by blackcompe: 06 June 2012 - 08:44 PM

Was This Post Helpful? 2
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Return Null or Return Empty

Posted 06 June 2012 - 08:45 PM

I typically return null, as it indicates a missing object entirely, and it's easy to check for null objects on the receiving end of the method call, as opposed to having to check the internals of an object. This is what I'm talking about:
public static Object getObject() {
    if (this_condition) {
        return new MyObject1();
    }
    else if (that_condition) {
        return new MyObject2();
    }
    else {
        return null
    }
}

public static void main(String[] args) {
    Object o = getObject();
    if (o != null) {
        do_stuff();
    }
    else {
        do_other_stuff();
    }
}



However, in the case of Singletons, GUI Components, and other objects that are critical to a system, you DO NOT want null objects, but instead to account for them internally. So, it's definitely a trade-off, but you have to use the proper method for the proper purpose.
Was This Post Helpful? 2
  • +
  • -

#4 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1954
  • View blog
  • Posts: 4,055
  • Joined: 11-December 07

Re: Return Null or Return Empty

Posted 07 June 2012 - 05:52 AM

Neither is better than the other. All these approaches are for different situations:

Null is for when there is no data.

Exceptions are for when something is wrong and the method cannot complete normally.

Empty collections are for when you ask for a list of everything and there just happen to be zero items. This is subtly different form no data.

Empty objects are dummy objects that are returned to simplify the calling code. This is down to design and philosophy. If you can go through all the methods and answer sensibly "What should this method return?" for every method on the object, you might have a case. But be careful. Is it always going to be correct for toString() to return "lol empty object", equals() to always return false, openFile() to always throw an IOException. Use this option cautiously because you might turn a trivial bug into a subtle one that appears a long way from the incorrect code.

Quote

So I tried the try - catch method and lo, the method now asks for a return object(seeing that the my return statement is wrapped in the try block). Eclipse then auto - generated a return null statement. Now, I'm pretty sure if I code correctly my program would never reach that line, but just to be sure I surfed a bit on the net and found out that an alternative is you could return an empty object.


This here sounds problematic to me. I'm sure your real method has more to it than this but it sounds like you have structured it like the following snippet, which has some code paths that do not return anything.

public IntenetAddress dummyMethod() {
    try {
        return getInternetAddress();
    } catch (SomeException e) {
        // log an error
        // or do something to recover
    }
    // No return here!
}


You could fix it like this. Now something gets returned on all code paths.

public IntenetAddress dummyMethod() {
    InternetAddress result = null;
    try {
        result = getInternetAddress();
    } catch (SomeException e) {
        // log an error
        // or do something to recover
    }
    return result;
}


I think your issue is what to do if your getter fails, not the dilemma over null or an empty object. Why would the getter fail? Is it because the field might not be set or because something the program relies on fails (e.g. file system or network) or is it because there may be an error in the program? These all require different solutions.

If it is because the field has not been set then returning null is probably the best option. I'd question why the getter didn't return null instead of throwing an exception.

If it is because some service failed, returning null is misleading. Null represents "no data", not a failed service. If you call the method again, the service might be available. Exceptions are the way to go. Maybe there is something your method can do to fix the problem. If not, just throw the exception. There are a few versions that could be useful:

// For when you can fix the problem
public IntenetAddress dummyMethod() {
    InternetAddress result = null;
    try {
        result = getInternetAddress();
    } catch (SomeException e) {
        // log an error
        // or do something to recover
        result = .......; // Make sure you fix the result variable!
    }
    return result;
}

// For when there is nothing you can do.
public IntenetAddress dummyMethod() throws SomeException {
    return getInternetAddress();;
}

// For when you can't recover but need to do some housekeeping
public IntenetAddress dummyMethod() throws SomeExceeption {
    InternetAddress result = null;
    try {
        result = getInternetAddress();
    } catch (SomeException e) {
        // log an error
        // or do something to recover
        throw e;
    }
    return result;
}


If the service fails but you know there is no reason it can (Be careful here. You can't make assumptions about file systems or networks even if you have just checked their status) or if the exception can only come about as the result of a bug then you can either follow the approach above or fail fast and quit the application. Another approach is to wrap the exception in a RuntimeException so you don't have to declare it. Again, be careful with this one!

Hope that helps!
Was This Post Helpful? 3
  • +
  • -

#5 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7649
  • View blog
  • Posts: 12,902
  • Joined: 19-March 11

Re: Return Null or Return Empty

Posted 07 June 2012 - 04:56 PM

I agree with much of the above. The only thng I want to add in is that if the method absolutely must not return a null, then you want to do something like
  Object returnObject;
  // try to create it
  // ...
  // blah, blah... 


  // before any return statement: 
  if returnObject == null throw new IScrewedUpImSorryException("Return object was null);  // or whatever exception works for you...
  return returnObject;


"Must not" means must not, period.
This is a simple example of the fail fast rule: always arrange to fail immediately and decisively rather than limping along on bad data, and always communicate the location of ant the reason for the failure as well as you are able.
Re-throwing exceptions is usually a bad idea. There's a reason that a method throws an exception: it's trying to tell you something. The further you let that get from the originating method, the harder it is to figure out just what happened. If you can catch and handle an exception immediately, that's usually the best thing to do.
Was This Post Helpful? 2
  • +
  • -

#6 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Return Null or Return Empty

Posted 07 June 2012 - 05:38 PM

Wow! Great answers, all. I guess it all boils down to design preference, but here I learn that returning null is more preferable. I usually do the second code example of cfoley. Thank you very much everyone. ^^
Was This Post Helpful? 0
  • +
  • -

#7 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1954
  • View blog
  • Posts: 4,055
  • Joined: 11-December 07

Re: Return Null or Return Empty

Posted 08 June 2012 - 01:30 AM

So have you decided how to handle your current problem?

Jon, I really like that and I don't know why it didn't occur to me before. Thanks!
Was This Post Helpful? 0
  • +
  • -

#8 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Return Null or Return Empty

Posted 12 June 2012 - 05:38 PM

Yes, I decided to do something like your third suggestion. Again, thanks! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1