Functions that return null

It is a bad idea to have functions return null. This is especially true for C/C++ libraries. Think of a hypothetical CharBuffer API:

#include <iostream>
#include <cstring>

class CharBuffer
{
public:
CharBuffer (const char* s) : buffer_ (NULL)
{
    size_t len = 0;
    if (s != NULL && (len = strlen (s)) > 0)
    {
        buffer_ = new char [len + 1];
        strcpy (buffer_, s);
    }
 }
 ~CharBuffer () { delete[] buffer_; }
 const char* GetBuffer ()
 {
    return buffer_;
 }
 private:
 char* buffer_;
};

This is a valid usage of the library, but it will result in the abnormal exit of the program:

int main ()
 {
    CharBuffer b ("");
    std::cout << b.GetBuffer () << '\n';
    return 0;
 }

There are two ways to cleanup the implementation of CharBuffer::GetBuffer():

  1. Throw an exception if buffer_ is NULL.
  2. Return a ‘default’ buffer object.

I prefer the second option as C++ do not have checked exceptions. Continuing with the above sample, we add a new static variable to the CharBuffer class:

static const char* DEFAULT_BUFFER;

and intilialize it like this:

const char* CharBuffer::DEFAULT_BUFFER = "";

The GetBuffer() function should return DEFAULT_BUFFER if buffer_ is NULL:

const char* GetBuffer ()
{
   if (buffer_ == NULL)
      return DEFAULT_BUFFER;
   return buffer_;
}

This gives the user to take appropriate action if the retuned value is the ‘default’ object. Even if he ignore to check it, the program will not behave badly. If the value to be defined is a complex type, and you need to return and non-const pointer, you can clone the DEFAULT_OBJECT and return the new copy.

This is a simple idiom, but can have important consequence on software quality as most of the errors caused by null pointers manifest at production sites. BTW, I was just wondering, do we really need NULL at all?