4Mar2008

In the original posting, Conditional Statements And Comparison Order, I brought up a coding style used by some software engineers that struck me as odd. The practice of placing a constant value first in a conditional comparison. For example:

if("Some String" == aVariable) {
  // Do some stuff
}
...

Listing 1

I never liked the way this reads in code and put forth the question, “why?” Well, this week I finally received an answer to that question. Some developers use this style in order to prevent an accidental assignment within a conditional. So if you forgot one of the equals like this:

if(aVariable = "Some String") {
  // Do some stuff every time, because the assignment returns a value
}

Listing 2

So instead of having a bug entrench itself into your code somewhere that it may be hard to trace, this would just cause a compiler error (or runtime error in the case of scripting languages).

Well, I still don’t like it. What do you think?



1 Comment

1

I am with you on this one. While it does make sense I still prefer to use the constant as the second value in a conditional statement.


 




Leave a comment