I recently read in Code Complete that the recommended way of handling expressions that involve numbers is to order them like a number line.
The book has 2 examples:
if ( (MIN_ELEMENTS <= i) && (i <= MAX_ELEMENTS) )
if ( (i < MIN_ELEMENTS) || (MAX_ELEMENTS < i ) )
With the first example showing that i is between the min and max elements, and the second example being that i falls outside the range between the elements.
I’ve been trying to adopt it, and I’m not sure if it’s just the way I think, but I don’t think it’s making code any clearer.
Example:
if (m_Health > BOSS_HALF_HEALTH) // The way it was
if (BOSS_HALF_HEALTH <= m_Health) // The "number line" method
Is it just me, or does the number line method seem less clear? What are your thoughts regarding this practice?
It’s also odd that he mentions putting constants on the left side of comparisons contradicts the number-line-method, but here it seems that the number line method leads to putting the constant on the left side.
I think the original motivation comes from having more than one comparison in the same logical expression. Both the quoted examples are comparing between both a lower and upper bound of a range. This ordering method may have value in those situations.
However, I don’t think it’s necessarily applicable if you’re testing a single condition, such as
m_Health > BOSS_HALF_HEALTH. In that case, the comparison you’re making is whether something (a variable) is greater than something else. That’s perfectly logical and doesn’t need to be ordered in any particular way.If you always ordered your comparisons in a “number line” way, you would never even need the
>or>=comparison operators. They exist for good reasons.