Ordering of numeric conditional tests

I’m reading Code Complete and something caught my eye in chapter 19. At first I wanted to argue with it, but the more I thought about it the more I liked it.

The idea concerns the situation where you need to test if a variable satisfies an inequality, for example, if you need to know if min < n < max. I’ve always done it like this:

if (x > min) && (x < max)
// -or-
if (x < lower) || (x > higher)

I did it this way because I liked having the comparison variable on the left and the constant on the right. McConnell suggested that the organization should look more like the inequality:

if (min < x) && (x < max)
// -or-
if (x < lower) || (higher < x)

I initially rebelled against this part of the chapter simply because it was not what I liked, but the more I think about it the more I like it. Almost every time I have to code an inequality like this I make a mistake, and I always write extra tests for these cases. I think if I start writing the conditions this way, I can increase the probability that I’ll get it right the first time.

1 thought on “Ordering of numeric conditional tests

  1. The second way is how my professors tend to write conditions like that, and I never really thought about it I guess, I used to do it the first way because it seemed more symmetrical, but at some point I realized that the second way does more closely reflect set notation, and it makes more sense to think of it logically as one condition of ” min < value < max ” rather than two separate tests.

Comments are closed.