Friday, November 16, 2012

Checking for NULL : Early returns or enclosing blocks?

Checking for NULL is a daily chore for every true to his salt programmer. We have come long way in programming languages and their implementations, however, this coder nemesis continues to flourish.
Now that we have ascertained the futility of thinking of doing away with the NULL check, lets try to make the best of it. What do you think is a better way of checking for NULL?

Approach #1

 if(pPointer == NULL)
    return; //possibly with error


Approach #2:

if(pPointer != NULL)
{
        ......
}


You could generalize this for any kind of error checking. The reason this post came up is because I have recently had a slight change of heart as to which is the better approach.

Disclaimer : I realize there is nothing that is "one-size-fits-all" in programming. There might be special situations when one is certainly better than the other. Let this be a very general case.

No comments: