Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In a condition statement (IF) everyone use (position < size), but why? Only convention or there is a good reason for that?

Example:

if (pos < array.lengh) {
   // do some with array[pos];
}

why not

if (array.lengh > pos) {
   // do some with array[pos];
}

?

share|improve this question
5  
One case where I don't mind having the "variable" on the right is if (MIN <= x && x <= MAX). (In some languages this can be written as MIN <= x <= MAX; in C, it's perfectly legal but doesn't mean what you might think it means). –  Keith Thompson Mar 12 '13 at 19:51
1  
possible duplicate of if ('constant' == $variable) vs. if ($variable == 'constant') –  gnat Mar 12 '13 at 22:04
5  
Might be related to how intervals are written [min, max] and not [max, min]. Therefore, it's only natural to check than an element x belongs to the interval by writing min <= x <= max. –  Andres F. Jun 12 '13 at 12:14
    
What a conumdrum. –  user61852 Jun 12 '13 at 20:52
add comment

8 Answers

up vote 37 down vote accepted

The deeper pattern is that we naturally use "[thing that varies] [comparison] [thing that does not vary]" as the standard order. This principle holds true for your example because position may vary, while size will not.

The only common exception is when testing for equality some programmers train themselves to use the opposite order in order to avoid the common variable = constant rather than variable == constant bug -- I don't hold with this idea because I find the natural ordering described above much more readable, primarily because it's the way we express the idea in English, and because most modern compilers will detect this and issue a warning.

share|improve this answer
3  
Depending on your development tools, many will also warn (or error) on the variable = constant construct. –  GalacticCowboy Mar 12 '13 at 18:55
5  
+1. Search "Yoda Conditions" for more details on the constant == variable phenomenon. –  John M Gant Mar 12 '13 at 20:15
    
I've seen this same thing recently in my own code base (e.g. if(DBNull == row["fieldName"]) methodCall() and wondered if I was going crazy because most of the time I've seen it done the other way around. –  Andrew Gray Mar 12 '13 at 20:28
1  
I would also add that (position < size) often expresses an upper bound, so in effect it's restating part of lowerbound <= position < upperbound, with the size as the upperbound. With the two constraints explicit, the position can only go in the middle. –  Steve314 Mar 12 '13 at 22:03
1  
It is probably related to language; we parse "X operator Y" as "X is (operator Y)", like the relation is a trait of X. By asking the comparison, we are asking whether X has a good or bad value (and Y is locally treated as a constant). Asking "pos < array.length" feels like asking: "Is the position okay (smaller than the array length)?" If no, something is wrong about the position; give me another position, and I would be happy to do what you wanted. But nothing is wrong about the array length. Asking "array.length > pos" feels like we should increase the array if it is too short. –  Viliam Búr Jun 12 '13 at 14:42
show 2 more comments

The only justification I've ever seen for it is that it is like number lines or other ordering things we learned in school. For example, we write number lines like this:

<--|--|--|--|--|--|-->
   1  2  3  4  5  6

The smaller things appear on the left of larger things. The same applies to other things such as dates (think of how a calendar is laid out).

It basically boils down to how we naturally think about the order of things. It is easier to read the first form because you don't have to do much mental processing on it.

share|improve this answer
    
You mean the expression that evaluates to the smaller value comes first in the condition ? How can you be sure that will be true if values change an runtime ? –  user61852 Jun 12 '13 at 21:00
    
@user61852 You don't need to know what the values are at runtime. Ex: I have 2 values that I calculate at runtime valueA and valueB and I want to test that valueA is smaller than valueB. I would write "if (valueA < valueB)". Whether valueA ends up being smaller than valueB is immaterial. Its easier (for me at least) to look at that and know that I'm looking for when valueA is smaller than valueB. If I were to see "if (valueB > valueA)" I have to stop and think about which thing is the smaller thing when I'm going to follow this branch of code. –  Becuzz Jun 12 '13 at 21:13
    
I missunderstood. I voted the answer down. Now I want to vote it up, but the site demands the answer to be edited so I can change my vote. Please do some edit so I can vote it up. –  user61852 Jun 12 '13 at 23:48
    
@user61852 You should be able to change your vote now. –  Becuzz Jun 24 '13 at 15:35
add comment

While it's mainly a matter of convention, it is my opinion that this best matches the way we think - it shows the item on which we place emphasis.

If we translate these to English, it would be the phrase "If the position is less than the array length", where the subject of the sentence is the transient item.

To express it the other way, "if the array length is greater than the position" puts the array length (assumed to be a fixed value) in the subject and the position (transient) becomes the direct object.

share|improve this answer
2  
Actually (in your last sentence) the position becomes the object of a preposition. But I agree with what you're trying to say. In linguistics we would say that position is the topic, and "less than array length" is the comment. "The tendency to place topicalized constituents sentence-initially (topic fronting) is widespread." en.wikipedia.org/wiki/… –  LarsH Mar 12 '13 at 20:57
add comment

My opinion, and this is only my opinion, is that it's a convention for readability. Although the two are identical, they feel different in my brain. I don't want to know if the array size is larger than pos. I want to know if pos is smaller than array size.

It's like a half-empty vs. half-full discussion. Mathematically identical, but my brain will see them differently depending on the context.

Personally, if I see

if (array.lengh > pos) {
    // do some with array[pos];
}

I will start thinking about whether or not that is a bug and what the programmer meant. Is he trying to do something other than bounds-checking?

Maybe I'm just not bright, but if I have to do that kind of analysis on every line of code, my brain hurts.

share|improve this answer
add comment

To express what some have tried to get at, in a different way...

When the order makes no difference to the behavior of the program, the difference is clearly a matter of what's most readable to humans. Here's a linguistic reason why putting the "topic" on the left makes sense:

In linguistics, the topic of a sentence is what is being talked about, and the comment is what is being said about the topic. In this example, we can assume that position is the topic, and "less than array length" is the comment. In English, and in many other languages, the topic is usually expressed before the comment. "The tendency to place topicalized constituents sentence-initially (topic fronting) is widespread." http://en.wikipedia.org/wiki/Topic_%28linguistics%29#Realization_of_topic.E2.80.93comment

So a good rule of thumb is to think of your line of code as a sentence (or clause, in this case), decide what the sentence is about, and put that first if you can. Often, what the sentence is "about" will be a variable rather than a constant. But sometimes the comment will also involve a variable, so you can't just go by that.

share|improve this answer
add comment

Personally, I prefer this:

bool positionIsWithinBounds = pos < array.length;
if (positionIsWithinBounds) {
   // do some with array[pos];
}

... it's more code, but is also very easy to read.

share|improve this answer
2  
+1 for giving the comparison a name. Really, though, I like this approach better for more complex conditionals, and not so much for simple cases like this. It actually makes me stop to think about "array", "bounds", "within", and what those all mean, when I instinctively know what it means for pos to be > array.length. In other words, even though it makes the meaning of the conditional very clear, it actually makes it a little harder to read IMO. –  John M Gant Mar 12 '13 at 20:20
add comment

As many other answers have said, it is very often easier to read:

[thing that varies] [comparison] [thing that does not vary]

Almost everyone I know uses this style exclusively.

There is one exception, for C-style languages which use = for assignment and == for comparison. If you accidentally type:

if (variable = 5) ...

instead of:

if (variable == 5) ...

then you will not get an error because this is a valid line of code. (Some compilers and IDEs will warn you about doing this, but it is still very easy to have such a simple typo.)

However, if you write:

if (5 == variable) ...

the compiler/interpreter will error because that is not a valid construct (in most languages, anyway).

This switch-around is often called a Yoda Condition.

UPDATE: Here is a list of places where Yoda Conditions are useful.

share|improve this answer
add comment

It's a matter of preference or convention. If you want to be consistent, there are two equally reasonable ways you could go about it:

  1. Always put the "subject" first (think of it as a sentence) - the value that the test is about. So for example you'd write if (age>5)

  2. Or always put the smaller element first (think of it as the values are ordered on your screen in the natural order). So for example you'd write if (a<b) regardless of whether this code is mostly about a or mostly about b.

Both conventions would recommend the first snipped you showed instead of the second, so I guess in this particular case you have your answer. I'd say it's wise to avoid writing code that violates both (1) and (2) here, as it'll make it harder to read for most people.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.