Site Sections

Saturday, March 21, 2009

A Comment on Standards

Hi All,

It's been a while since I posted, but I have an interesting little tid big that I ran into today. Apparently some standards state that you should always define your null checking logic as follows:

if ( null == var )
{
// do whatever
}

instead of:

if ( var == null )
{
// do whatever
}

Apparently the reason for this is that it will always avoid a dreaded assignment error causing a null pointer in your application. I.E.:

if ( var = null )
{
// This will do bad things to your code.
}

It avoids them because the compiler will not allow you to assign a value to null where as you can assign null to a variable. This same logic holds true for any constant. I.E.:

if ( 1 == var )
{
// do something spiffy
}

as well as any variable declared as a const, and enumerated values as well, since these are converted by the compiler to be a constant. However, I plan on still doing things the old fashion way, as bad habits are hard to break. I just thought it was an interesting idea and thought I would share.

Later.

No comments: