Conditional Statements And Comparison Order

Most programming languages that I know and can think of use conditional tests and comparison operators. This is one of the most basic concepts in programming. A conditional test at it’s most basic form is testing whether a variable’s value is less than, equal to or greater than a constant or known value. You then make a decision to do or not to do something based on the results of that comparison. For instance take the following example:

Listing 1

In this example, MoneyInMyWallet is a variable that should hold the value of the amount of money in my wallet at any given time. The condition says that if that amount is greater than $100, then I can go shopping. If the amount is less than or equal to $100 then I cannot go shopping. Pretty simple, right?

What’s Your Point?

No, this actually is not a tutorial on conditional statements and programming. My point is I’ve noticed that some developers will actually place the known value as the first item in the comparison. What do I mean? Let me demonstrate using our previous example:

Listing 2

Now this comparison will give you the exact same results as the first iteration. My question is, why would you want to write the statement like this? Why do I care? Well, I don’t know what it is but something just feels funny or odd about writing it that way. Reading a conditional statement will help my point. You would read the first listing, “if the amount of money in my wallet is more than $100.” Ok, now the second listing would be, “if $100 is less than the amount of money in my wallet.” Does it seem odd to you to say if $100 is less than…? That part of the conditional is the known value portion and so it doesn’t feel right for my to say, “if my known value is…” and then plug in your variable value. After all it’s the variable value that we are really testing, right?

What do you think? Do you prefer one way over another? Or do you just slap your variables into the conditional all willy-nilly? (hee hee… he said willy-nilly)