Is it better to return NULL or empty values from functions/methods where the return value is not present?

  • I am looking for a recommendation here. I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

    Take the following two methods as an examples:

    string ReverseString(string stringToReverse) // takes a string and reverses it.
    Person FindPerson(int personID)    // finds a Person with a matching personID.
    

    In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that. Also, this way, the caller would not have to check to see if a NULL was returned.

    In FindPerson(), returning NULL seems like a better fit. Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()). So why not just return NULL here and then the caller only has to check for NULL.

    Does anyone else struggle with this? Any help or insight is appreciated.

    It will vary. You could also argue that the method should stop values which are incorrect up front, for instance your stringToReverse parameter being passed in as empty or null. If you performed that check (threw back an exception), it will always return something other than null.

    Fowler POEAA - p. 496 Base Patterns - Special Case(null object) Bloch Effective Java, 2nd Edition Item 43: Return empty arrays or collections, not nulls

    @Boris I didn't see your comment. I actually just posted Special Case as an answer.

    @Thomas I don't see any problem in it :). As for the question it's a matter of common sense anyway.

    An interesting comment is that in Oracle databases NULL and the empty string are the same

    be consistent. Always returns nulls, A string can be null'ed so you want to expose this to your user and it their responsibility to check for nulls. You can't unforutently apply that to native types like int and long but you can if you used the ? keyword. So Int? but it just makes things really weird.

    Depends on your team consensus: in the case of mine, we agreed to return `null` for method that returns a single object indicating a value is not found. For method that return multiple objects (list, enumerable, array), we return `empty list of object`. It's all about consistency and convention.

  • JW8

    JW8 Correct answer

    9 years ago

    StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

    Returning null is usually the best idea if you intend to indicate that no data is available.

    An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

    Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

    Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

    However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

    In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.

    _Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place._ Never understood this argument. The null check is what, at most < 10 chars? Why do we act like this is back bending labor?

    Not to mention that some languages will do it for you ("?." in Groovy, IIRC)

    Nobody said it was back bending labor. But it *is* labor. It adds a special case to the code which means one more branch to test. Plus, it disrupts the flow of the code. `for x in list_of_things() {...}` is arguably quicker to grok then `l = list_of_things(); if l != null {...}`

    @Bryan: there is a big difference between an empty list of values, and an empty string. A string seldom represents a list of characters.

    @kevin cline: of course. But in the case of a string, you may want that string to appear in a log whether it's null or not. Having to check if it's null so you can print an empty string obfuscates the real intent. Or perhaps it's something like database field that contains user-contributed content that you want to add to a web page. It's easier to do `emit(user.hometown)` than `if user.hometown == null { emit("") else {emit(user.hometown)}`

    Not only is it extra typing (not a big deal), but it affects readability. I personally find code with a bunch of null checks distracting.

    @AaronMcIver: It's only 10 chars... _every time you call it._ Now, if you're a fan of AOP, there are some very nice ways to solve this problem.

    How about when you are returning a guid? An empty guid is 00000000-0000-0000-0000-000000000000. Should an api return null or 000... ? I would say it should return 000...

    return optional instead.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM