Monday, June 14, 2010

Which came first, the variable or the literal?

Today I received the feedback from a code review one of my peers did of my code and they asked a question about a particular coding style technique I use.  Specifically they asked why when comparing a variable to a literal value I always put the literal value on the left side of the operator?  Put another way, why do I do this:
if(null == someVariable)
instead of this:
if(someVariable == null)

After all, this person pointed out, the second method is more easily read as "someVariable equals null" as opposed to "null is equal to the value of someVariable."  I think that's a fair point and while I'm a big proponent of increasing the readability of code this is an instance where I'll take the hit.

My habit of putting the literal value before the variable comes from dealing with Javascript.  When coding Javascript I might check to see if a value is set to zero, like this:
if(someVariable = 0)

Maybe that looks good to me because I haven't had my third espresso of the day - but it introduces a bug in my code.  I fat-fingered the operator and put = instead of ==.  So now the statement isn't doing an evaluation, it's doing an assignment.  I'm not going to catch that as part of a compile because Javascript is not compiled.  And it's not going to raise a run-time error because it's syntactically valid.

But it's not going to do what I want it to do.

Because I've been burned by this in the past I got in the habit of putting the literal on the left side of the operator.  Because while I still won't get any compile-time love I will get a run-time error when the code says:
if(0 = someVariable)

Yes, the code review was being done against some of my C# code so the same risk isn't there.  But I don't feel like changing this habit from language to language.  Especially where I'm doing ASP.NET and am jumping between C# and Javascript all day anyway.