You can start by eliminating NULL sources:
Edit
if (error) { return NULL; }
IN
if (error) { return DefaultObject;
If the returned objects are not applied by default, and your code base already uses exceptions, do
if (error) { throw BadThingHappenedException; }
Then add the treatment to the appropriate places.
If you work with legacy code, you can make some shell functions / classes:
ResultType *new_function() { ResultType *result = legacy_function(); if (result) { return result; } else { throw BadThingHappenedException; } }
New functions should start using new functions and have proper exception handling.
I know that some programmers just don't get exceptions, including smart people like Joel . But what ends up returning NULL is that this NULL goes crazy, as everyone just thinks that it is not their business to deal with this and return silently. Some functions may return an error code, which is good, but the caller often finishes returning still-more-NULL in response to errors. Then you see a lot of NULL checks in each individual function, no matter how trivial the function is. And all that is required is just one place that does not verify that NULL crashes into the program. Exceptions make you think carefully about the error and decide exactly where and how to handle it.
It seems you are just looking for simple solutions like static analysis tools (which you should always use). Changing link pointers is also a great solution. However, C ++ has the beauty of RAII, which eliminates the need for "try {} finally {}" everywhere, so I think it's worth your serious consideration.
source share