Dealing with NULL pointers is always a pain, because it could be that the pointer being NULL is completely acceptable or it could mean that it's broken, but it's hard to know which without digging into the code many times.
I came across this while working on some shared code the other day. Another group had created a macro that looked something like this (although much more crazy):
#define mustDeref(p) if(!p) assert(line, file, etc);*p;
So essentially all it does is check to see if the pointer is null and then assert if it is. If it's not, it returns the dereferenced pointer. That turns code into something like this:
void function( int *ptr )
{
int &ref = mustDeref(ptr);
// use ref like a reference now instead of a pointer
}
of course some people don't like to do that and get lazy, so you see a lot of stuff like this:
mustDeref(parentclass).membervar;
Aaaand, then of course you get stuff like this (which is an actual line of code):
*(
mustDeref(
mustDeref(
mustDeref(
mustDeref(
mustDeref(
tgt.
GetOuter()).
GetOuter()).
GetOuter()).
GetOuter()).
GetOuter()).
GetName())
And we all know that's just fucking ugly. I talked to some of the guys who used it and they swear by it saying that it pushes bad null pointers up the stack into the function in which it's actually null. My god though, it just breeds ugly code. I would much, much prefer having an assert wherever necessary and then continue using the pointer as-is. The assert isn't going to catch a bad pointer, only a null one, so it doesn't make sense to use anything other than an assert, especially when it clutters up the code. This just reeks of someone trying to fix something and causing more problems than it's worth, especially because it clutters up the code to be hard to read and disgusting looking.
So ya, don't write extra code to do something that's already possible and make it look uglier in the process. BAD.
Tags: programming