views:

1326

answers:

21

I've heard some voices saying that checking for a returned null value from methods is bad design. I would like to hear some reasons for this.

pseudocode:

variable x = object.method()
if (x is null) do something
+25  A: 

Who says this is bad design?

Checking for nulls is a common practice, even encouraged, otherwise you run the risk of NullReferenceExceptions everywhere. Its better to handle the error gracefully than throw exceptions when you don't need to.

Brandon
+1. Code that throws exceptions for problems that can be mitigated on the spot makes me sad.
Hooked
Yeah, imagine if every time you search on Google and got no results it threw an exception? Crazy! Lots of methods in the .NET framework can return null, so why shouldn't our own code do the same, when appropriate?
Dan Diplo
How sad do you get when coders forget to check for nulls and then get mysterious null pointer exceptions? Checked exceptions, where the compiler reminds the user they didn't deal with error conditions avoid taht class of coding errors.
djna
@djna: I guess this is also sad but I've found that the same type of coders that "forget" to check for nulls are the ones who when dealing with checked exceptions frequently end up swallowing them.
Tuzo
It's easier to spot the presence of an empty catch block than the absence of a null-check.
Preston
@Tuzo, that's unfortunately true. But I agree with Preston that that we can spot these quite easily, and educate the offenders ;-)
djna
What would be better is if there were non-nullable reference types in C#. This is possible with Code Contracts in C# 4.0 but requires a little extra work (and patience waiting for .NET 4.0 to ship).
Joe Chung
@Preston: I strongly disagree. Absence of a null-check you'll spot immediately, when it crashes. Swallowed exceptions can propogate mysterious and subtle errors for years...
Beska
A: 

G'day,

Returning NULL when you are unable to create a new object is standard practise for many APIs.

Why the hell it's bad design I have no idea.

Edit: This is true of languages where you don't have exceptions such as C where it has been the convention for many years.

HTH

'Avahappy,

Rob Wells
If you are unable to create an object, you should really throw an Exception. If you are unable to find an object that matches some query, then returning null is the way to go.
Thilo
@Thilo, show me how to do that in C and I'll be most interested.
Rob Wells
+11  A: 

Based on what you've said so far, I think there's not enough information.

Returning null from a CreateWidget()method seems bad.

Returning null from a FindFooInBar() method seems fine.

jcollum
+1  A: 

For certain scenarios, you want to notice a failure as soon as it happens.

Checking against NULL and not asserting (for programmer errors) or throwing (for user or caller errors) in the failure case can mean that later crashes are harder to track down, because the original odd case wasn't found.

Moreover, ignoring errors can lead to security exploits. Perhaps the null-ness came from the fact that a buffer was overwritten or the like. Now, you are not crashing, which means the exploiter has a chance to execute in your code.

Drew Hoskins
+5  A: 

It depends on the language you're using. If you're in a language like C# where the idiomatic way of indicating the lack of a value is to return null, then returning null is a good design if you don't have a value. Alternatively, in languages such as Haskell which idiomatically use the Maybe monad for this case, then returning null would be a bad design (if it were even possible).

Greg Beech
+57  A: 

The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.

For example, if I were to define a method in Java that returned a Collection I would typically prefer to return an empty collection (i.e. Collections.emptyList()) rather than null as it means my client code is cleaner; e.g.

Collection<? extends Item> c = getItems(); // Will never return null.

for (Item item : c) { // Will not enter the loop if c is empty.
  // Process item.
}

... which is cleaner than:

Collection<? extends Item> c = getItems(); // Could potentially return null.

// Two possible code paths now so harder to test.
if (c != null) {
  for (Item item : c) {
    // Process item.
  }
}
Adamski
+1 for the Null Object Pattern
Carl Manaster
Yes, way better than returning null and hoping the client remembers to deal with the case.
djna
I'll happily agree that returning null is insane when it's used as a substitute for empty containers (or strings). That's not the common case though.
MSalters
+1 for the Null Object Pattern for me too. Also when I actually want to return null, I have been naming the method like getCustomerOrNull() to make it explicit. I think a method is named well when the reader doesn't want to look at the implementation.
Michael Valenty
The comment '// Two possible code paths now' is not correct; you have two code paths in either way. However, with the null Collection object in your first example, the 'null' code path is shorter. You still have two paths though, and you still need to test two paths.
Frerich Raabe
+3  A: 

It's fine to return null if doing so is meaningful in some way:

public String getEmployeeName(int id){ ..}

In a case like this it's meaningful to return null if the id doesn't correspond to an existing entity, as it allows you to distinguish the case where no match was found from a legitimate error.

People may think this is bad because it can be abused as a "special" return value that indicates an error condition, which is not so good, a bit like returning error codes from a function but confusing because the user has to check the return for null, instead of catching the appropriate exceptions, e.g.

public Integer getId(...){
   try{ ... ; return id; }
   catch(Exception e){ return null;}
}
Steve B.
Yup. If you've got an error condition, throw an exception.
David Thornley
This is one case where an exception would be warranted. If you're requesting the name of an employee that doesn't exist, something is obviously going wrong.
Thorarin
I think that's a bit literal, Thorarin-you can quibble with my example, certainly, but I'm sure you can imagine some instance of a function that returns a matching value, or null if there's no match. How about getting a value from a key in a hashtable? (should've thought of that example in the first place).
Steve B.
A hash table returning null for a key that doesn't exist is bad. Doing so automatically means that you can't store null as a value without inconsistent code.
RHSeeger
A: 

Other options to this, are: returning some value that indicates success or not (or type of an error), but if you just need boolean value that will indicate success / fail, returning null for failure, and an object for success wouldn't be less correct, then returning true/false and getting the object through parameter.
Other approach would to to use exception to indicates failures, but here - there are actually many more voices, that say this is a BAD practice (as using exceptions may be convenient but has many disadvantages).
So I personally don't see anything bad in returning null as indication that something went wrong, and checking it later (to actually know if you have succeeded or not). Also, blindly thinking that your method will not return NULL, and then base your code on it, may lead to other, sometimes hard to find, errors (although in most cases it will just crash your system :), as you will reference to 0x00000000 sooner or later).

Ravadre
A: 

Unintended null functions can arise during the development of a complex programs, and like dead code, such occurrences indicate serious flaws in program structures.

A null function or method is often used as the default behavior of a revectorable function or overrideable method in an object framework.

Null_function @wikipedia

Juicy Scripter
+3  A: 

It's not necessarily a bad design - as with so many design decisions, it depends.

If the result of the method is something that would not have a good result in normal use, returning null is fine:

object x = GetObjectFromCache();   // return null if it's not in the cache

If there really should always be a non-null result, then it might be better to throw an exception:

try {
   Controller c = GetController();    // the controller object is central to 
                                      //   the application. If we don't get one, 
                                      //   we're fubar

   // it's likely that it's OK to not have the try/catch since you won't 
   // be able to really handle the problem here
}
catch /* ... */ {
}
Michael Burr
Though you can log a diagnostic error right there, then maybe rethrow the exception. Sometime First Failure Data Capture can be very helpful.
djna
Or wrap the exception in a RuntimeException with diagnostic information in the message string. Keep the information together.
Thorbjørn Ravn Andersen
A: 

What alternatives do you see to returning null?

I see two cases:

  • findAnItem( id ). What should this do if the item is not found

In this case we could: Return Null or throw a (checked) exception (or maybe create an item and return it)

  • listItemsMatching (criteria) what should this return if nothing is found?

In this case we could return Null, return an empty list or throw an Exception.

I believe that return null may be less good than the alternatives becasue it requires the client to remember to check for null, programmers forget and code

x = find();
x.getField();  // bang null pointer exception

In Java, throwing a checked exception, RecordNotFoundException, allows the compiler to remind the client to deal with case.

I find that searches returning empty lists can be quite convenient - just populate the display with all the contents of the list, oh it's empty, the code "just works".

djna
Throwing exceptions to indicate a condition which is expected to possibly happen during the normal flow of the program leads to really ugly code, of the sort try { x = find() } catch (RecordNotFound e) { // do stuff }.
quant_dev
Returning empty lists is a good solution but only when the method is in a context that can return lists. For "findById" situations, you need to return null. I don't like RecordNotFound exceptions.
Thilo
So that's the crux of our differentce in opinion. To my eyes there's not much difference in beauty between x = find(); if ( x = null ) { work } else { do stuff } and try catch. And, if necessary I'm prepared to sacrifice beauty for code correctness. Too often in my life I encounter code where return values have not been checked.
djna
A: 

Well, it sure depends of the purpose of the method ... Sometimes, a better choice would be to throw an exception. It all depends from case to case.

Sapphire
+22  A: 

Here's the reason.

In Clean Code by Robert Martin he writes that returning null is bad design when you can instead return, say, empty array. Since expected result is an array, why not? It'll enable you to iterate over result without any extra conditions. If it's an integer, maybe 0 will suffice, if it's a hash, empty hash. etc.

The premise is to not force calling code to immediately handle issues. Calling code may not want to concern itself with them. That's also why in many cases exceptions is better than nil.

hakunin
This is the Null Object Pattern mentioned in this answer: http://stackoverflow.com/questions/1274792/is-returning-null-bad-design/1274822#1274822
Scott Dorman
The idea here is that on error, you return an empty/blank version of whatever object type you would return normally. An empty array or string would work for those cases, for instance. Returning "NULL" is appropriate when you would normally return a pointer (since NULL is essentially an empty pointer). Returning NULL on error from a function that normally returns, say, a hash can be confusing. Some languages handle this better than others but in general, consistency is the best practice.
bta
You don't necessarily return on error, unless the error is somehow controlling the flow (which is not a good practice) or abstracted in API or interface. Errors are there to propagate to any level on which you decide to catch it, hence you don't have to deal with it in calling context. They are by default null-object-pattern-friendly.
hakunin
+2  A: 

Exceptions are for exceptional circumstances.

If your function is intended to find an attribute associated with a given object, and that object does has no such attribute, it may be appropriate to return null. If the object does not exist, throwing an exception may be more appropriate. If the function is meant to return a list of attributes, and there are none to return, returning an empty list makes sense - you're returning all zero attributes.

If you try to _use_ an attribute with no value, that merits an exception. (I'm assuming your spec says the attribute is optional.) Have a separate method to check whether its value has been set.
Preston
+6  A: 

Good uses of returning null:

  • If null is a valid functional result, for example: FindFirstObjectThatNeedsProcessing() can return null if not found and the caller should check accordingly.

Bad uses: Trying to replace or hide exceptional situations such as:

  • catch(...) and return null
  • API dependency initialization failed
  • Out of disk space
  • Invalid input parameters (programming error, inputs must be sanitized by the caller)
  • etc

In those cases throwing an exception is more adequate since:

  • A null return value provides no meaningful error info
  • The immediate caller most likely cannot handle the error condition
  • There is no guarantee that the caller is checking for null results

However, Exceptions should not be used to handle normal program operation conditions such as:

  • Invalid username/password (or any user-provided inputs)
  • Breaking loops or as non-local gotos
ZeroConcept
"Invalid username" seems like a good cause for an Exception, though.
Thilo
Users entering invalid login/passwords should not be treated as an exceptional conditions, its part of normal program operation. However, the authentication system failing to respond (e.g. active directory) is an exceptional condition.
ZeroConcept
see:http://stackoverflow.com/questions/77127/when-to-throw-an-exception
ZeroConcept
I'd say it depends: `boolean login(String,String)` seems fine and so does `AuthenticationContext createAuthContext(String,String) throws AuthenticationException`
sfussenegger
A: 

Sometimes, returning NULL is the right thing to do, but specifically when you're dealing with sequences of different sorts (arrays, lists, strings, what-have-you) it is probably better to return a zero-length sequence, as it leads to shorter and hopefully more understandable code, while not taking much more writing on API implementer's part.

Vatine
A: 
return NULL; //is great!
ufukgun
A: 

If the code is something like:

command = get_something_to_do()

if command:  # if not Null
    command.execute()

If you have a dummy object whose execute() method does nothing, and you return that instead of Null in the appropriate cases, you don't have to check for the Null case and can instead just do:

get_something_to_do().execute()

So, here the issue is not between checking for NULL vs. an exception, but is instead between the caller having to handle special non-cases differently (in whatever way) or not.

Anon
A: 

If you read all the answers it becomes clear the answer to this question depends on the kind of method.

Firstly, when something exceptional happens (IOproblem etc), logically exceptions are thrown. When exactly something is exceptional is probably something for a different topic..

Whenever a method is expected to possibly have no results there are two categories:

  • If it is possible to return a neutral value, do so.
    Empty enumrables, strings etc are good examples
  • If such a neutral value does not exist, null should be returned.
    As mentioned, the method is assumed to possibly have no result, so it is not exceptional, hence should not throw an exception. A neutral value is not possible (for example: 0 is not especially a neutral result, depending on the program)

Untill we have an official way to denote that a function can or cannot return null, I try to have a naming convention to denote so.
Just like you have the TrySomething() convention for methods that are expected to fail, I often name my methods SafeSomething() when the method returns a neutral result instead of null.

I'm not fully ok with the name yet, but couldn't come up with anything better. So I'm running with that for now.

borisCallens
A: 

Make them call another method after the fact to figure out if the previous call was null. ;-) Hey, it was good enough for JDBC

David Plumpton
+1  A: 

Its inventor says it is a billion dollar mistake!

Bahadır