
Don't use the greater-than sign in programming (2016) - sheharyarn
http://llewellynfalco.blogspot.com/2016/02/dont-use-greater-than-sign-in.html
======
danShumway
I really think this is just bikeshedding over style.

If we were optimizing for readability and predictability, we'd standardize on
the most commonly used format.

``if (x > 5 && x < 10)``

Putting a rule that variables should always be on the left hand side of a
comparison also gives you only 2 ways to write any conditional, so it's just
as good as getting rid of ``>``. It also has the advantage of being by far the
most widespread way that people already write conditionals, so you don't need
to hold a team meeting where you explain to a bunch of grumpy senior
programmers why even though they _think_ their coding style is easier to read
it actually isn't.

But by far the best option is to not have a meeting at all and to not care
about things like this. In the absence of real, tangible data that conditional
styles are causing bugs, these kinds of debates are very often a pre-
optimization, and pre-optimization should be avoided.

When I put the effort into tracking and ordering the root causes of the
majority of bugs in my software (both in personal projects and in large
corporate environments) I am often surprised at the results. Very rarely are
they consistent with the causes I would have predicted.

That's why I call things like this bikeshedding. In a large organization, it
is probably more productive for you to hold another meeting about
encapsulation and code reviews than it is for you to start up a Slack
discussion about what style people use on their conditionals.

~~~
userbinator
_But by far the best option is to not have a meeting at all and to not care
about things like this._

Indeed. This article reads like someone who doesn't understand inequalities,
and proposes a quite possibly hazardous shortcut to it instead. To not
understand such basic maths is baffling (this is primary-school stuff), and I
wonder at the state of maths education these days to see adults struggling
with these concepts.

I have never _in over 3 decades_ of programming ever had to ask myself the
question of how to write conditional expressions --- it's something that comes
naturally, and in this specific case I would also write it with the variables
on the left.

~~~
cmroanirgo
Agreed.

That said, I've come across code where the variable is _always_ on the right.
This often seems to be a throwback for some devs to alleviate the problem of
mixing up equality and assignment.

That is, it seems that some people have been taught to use this expression (&
stick to it religiously):

if (5 == x) ...

simply so that if they make a mistake and type

if (5 = x) ...

the (C/C++) compiler will reject it. So, these people always write the
slightly more awkward case (imho) of:

if (5 < x && 10 > x) ...

but to me it doesn't read as cleanly, because we don't _say_ it that way.

Of course, there's the problem of understanding the meaning of 'between' which
can be inclusive of the end points, or exclusive...and you really can't tell
from the english. In every case, it needs to be clarified. (eg 'pick a number
between 1 and 10'):

if (x>=1 && x<=10)...

------
fl0wenol
Qualification: Don't use the greater sign when doing range checks.

Counter-point: When checking if a variable is greater than a constant, using
the less than is very confusing since we read left to right.

if(x > LIMIT) {

Read "If x exceeds LIMIT, then"

The opposite reads like "If the LIMIT is less than x", which sounds strange
and emphasizes the wrong thing, implying LIMIT changed, not x.

~~~
BurningFrog
Yeah, I think the article has a point for complex/chained expressions.

But if the way you think about the domain is "if x is larger than LIMIT..."
you should write it `if (x > LIMIT)`!

------
nostrebored
This is incredibly poorly thought out. You don't only use conditionals while
iterating. Even if you did, wanting to have a math like notation isn't
necessarily reasonable. When reading a simple multi-part inequality like 5 < x
< 10 I don't think "when 5 is less than x", I still think about it in terms of
the variable. The benefit of arranging things in a simple inequality like
above is the shorthand notation. You don't get that with:

5 < x && x < 10 vs. x > 5 && x < 10

------
jamesbrennan
Clojure has a nice way of achieving

    
    
      (5 < x && x < 10)
      This is a nice way of expressing "x is between 5 and 10" 
      because it is literally between 5 and 10. 
    

which is that the < function can take any number of arguments:

    
    
      (< 5 x 10)
    

[https://clojuredocs.org/clojure.core/%3C](https://clojuredocs.org/clojure.core/%3C)

------
fooker
Ah,
[https://en.wikipedia.org/wiki/Yoda_conditions](https://en.wikipedia.org/wiki/Yoda_conditions)

~~~
gmueckl
Should I be worried that such a trivial thing has a name and a Wikipedia
entry? What is the actual relevance here?

~~~
saagarjha
> Should I be worried that such a trivial thing has a name and a Wikipedia
> entry?

It has non-trivial advantages and drawbacks, which are interesting to
document.

------
deathanatos
I use this. I can read lines reading left to right with only </<= _very_
quickly now, because of the visualization of a numberline in my head. Any
other arrangement, and I have to slow down to my old, normal processing, and
reason _very_ carefully about the code, lest a subtle bug slip by.

For similar reasons, I find this notation helps me prevent errors, because
they become visually detectable.

~~~
kccqzy
Sure if you have

    
    
        5 < x && x < 10
    

you can use the number line visualization very quickly, but it breaks down if
the code is in fact

    
    
        x < 10 && 5 < x
    

It means the same thing. But it's not obvious.

So the number line analogy is incomplete and even when there is only </<= you
still need careful reasoning.

------
lurquer
I had to write a scripting language for a personal project. Since I could
create whatever syntax I wanted, I used this:

'if x==4' was written as 'x[4]'

'if x>2 && x<4' was written as 'x(2,4)'

'if x>=2 && x<4' was written as 'x[2,4)'

Etc.

It was very easy to read and write... at least for me.

~~~
gbear605
What if you wanted ‘if x>2 || x < -2’?

~~~
thaumasiotes
That's not exactly a challenge for the syntax...

    
    
        if-not x[-2,2]
    

Just like you'd write x ∉ [-2,2] with pen and paper.

------
nemo1618
Ha, I've been using this trick for a while, though I wouldn't go so far as to
say "don't use the greater-than-sign." Honestly I just wish languages had a
cleaner way to write "x is within this range," e.g. "if x in [2,4)"

~~~
qihqi
In Python we have if 2 <= x < 4.

~~~
applecrazy
There's also `if x in range(2,4)`, which translates to `if x in the interval
[2, 4)`.

~~~
saagarjha
Is this efficient? I was under the impression (which is likely inaccurate,
because I'm no expert on Python) that range returned a generator or a list
outright, making this an O(n) operation.

~~~
applecrazy
You're correct. It returns a list from from [a, b), but it's just another
example of some expressive (albeit computationally inefficient) notation
Python has.

Edit: I take that back. Here's a section from Python's range() documentation:

> The advantage of the range type over a regular list or tuple is that a range
> object will always take the same (small) amount of memory, no matter the
> size of the range it represents (as it only stores the start, stop and step
> values, calculating individual items and subranges as needed).

So it may be a O(1) operation under the hood.

~~~
kilburn
No, what the docs say is that range is a generator. It never stores the entire
list of values, but it _does_ iterate through all the numbers, spitting them
out one by one (hence it uses O(1) memory, but O(n) computation).

Equivalent pseudocode:

    
    
      function in_range(x, a, b):
        for i=a; i<b; i++:
          if x == i return true
        return false

------
giomasce
Another article along the lines of "I personally prefer to use a syntax in a
certain case, therefore everybody should use the same syntax in every case,
and really I do not understand why the language creators even allowed for the
other syntax".

No, your are not smarter than everybody else. You just have different tastes,
and you are not even covering all possible use cases (I would say that most
people find "x > 0" more legible than "0 < x").

A lot of "Don't do" or "X considered harmful" article writers should really be
a bit more careful before generalizing from "I like" to "everybody should" so
quickly.

------
johnday
This just seems like an argument against putting the variable on the right
hand side of the comparator.

You _also_ only end up with two options, in the same way, and IMO (x > 5 && x
< 10) is much more readable than (5 < x && x < 10) .

------
nimbius
as a CS major im sure this has academic value. as someone who is just learning
python outside of a trade job as an engine mechanic, this idea makes me want
to glass someone and im not sure why.

(5 < x && x < 10)

if we're talking about X, whats wrong with defining the parameters of its
constraints in terms of X instead of dancing around the numbers? 5 < X makes
it sound like im setting constraints on the number 5.

~~~
manojlds
In python you can just do 5 < x < 10

~~~
wongarsu
which is also the proper way you would read in any scientific paper, and very
easy to read imho.

5 < x && x < 10 is the attempt to replicate this in other languages but falls
a bit short

~~~
saagarjha
> 5 < x && x < 10 is the attempt to replicate this in other languages but
> falls a bit short

On the contrary, it's Python that added the shorthand, mathematical-looking
notation because the longer "desugared" form wasn't great.

~~~
kilburn
That's not the contrary, it is exactly what the other comment said ;). "To
fall short" == "to not be great"

------
fouc
This article is too basic.

> (x < 10 && 5 < x) which is a stupid option because it implies 10 < 5

What? no it doesn't!

> (5 < x && x < 10)

It's already very obvious that one can take 5 < x < 10 and split it into 5 < x
&& x < 10 right off the bat. Loads of examples of that out there.

------
dextersgenius
[http://4.bp.blogspot.com/-vglPHDBuUgI/VsniES7XnKI/AAAAAAAAD9...](http://4.bp.blogspot.com/-vglPHDBuUgI/VsniES7XnKI/AAAAAAAAD9k/7Evjten2ujI/s1600/Screen%2BShot%2B2016-02-21%2Bat%2B11.11.06%2BAM.png)

The number line representation is incorrect. (5 < x && x < 10) represents x
has possible values of 6,7,8,9 (assuming x is int), whereas the number line
shows that 5 and 10 are inclusive, but that's not the case as per the provided
example.

~~~
saagarjha
Because all of the author's number line representations are consistent, I
think you can consider them placing an implicit "open circle" on the bounds of
all those ranges on the number line.

------
benblu
"Go ahead and find out which one, I'll wait" ... As if it required herculean
effort.

"which is a stupid option because it implies 10 < 5" No it doesn't.

And I stopped reading.

~~~
anothergoogler
Eventually, cognitive decline will win the day and I will be confused by
simple use of conditional operators. Until then, I'm with you pal.

------
userbinator
The bigger problem here is that if you say...

 _Let 's say that I want to check that something is between 5 and 10._

...you did not specify explicitly whether the ends are inclusive/exclusive,
and IMHO that (and the off-by-one errors it causes) is far more important.

Related: I've more than once had to ask someone whether "I will be away from
23 to 27" was inclusive or exclusive for the 27, because e.g. "meeting from 10
to 11" usually is _exclusive_ at the upper end.

------
shmerl
Removing something doesn't necessarily make it more convenient to use. I'd
find it bizarre if some language won't provide > using this logic.

------
shurcooL
I prefer to use the “5 < x && x < 10” style as well.

I’ve arrived to the same general conclusion independently, which is
reassuring.

~~~
vortico
Same with me, although I feel that putting the variable last is a form of Yoda
programming.
[https://en.m.wikipedia.org/wiki/Yoda_conditions](https://en.m.wikipedia.org/wiki/Yoda_conditions)

------
brudgers
Lately, I am enamored of Ruby

    
    
      x.between?(6,9)
    

or very explicitly

    
    
      x.between?(5.0.next_float, 10.0.prev_float)

~~~
ascar
But you have to know if the boundaries are inclusive or exclusive, which
leaves you with four different possibilities. You and everyone who reads your
code needs to know this.

Ruby is my main language and I would have to look up the boundaries of this
function.

Your "explicit" statement is also so much worse than using `x < 5.0` or `x <=
5.0`, depending on what you want. This is terrible advice imho.

~~~
brudgers
I am lately enamored of Ruby because it helps me write code that makes me
happy. Calling methods on numbers is one of those things that does.

Anyway, ranges are another way of expressing the concepts in Ruby:

    
    
      (5.0.next_float..10.0.prev_float).include?(x)
    

or

    
    
      (5.0.next_float...10).include?(x)
    

if I don't mean

    
    
      (5..10).include?(x)
    

None of which is advice. Just remarks about why I am enamored of Ruby, lately.
If I wanted to write C, I'd use Go.

------
zapzupnz
This all looks good to me until I'm unwrapping an optional and checking it's
length in Swift, which normally looks like:

    
    
        guard let array = obj.someArray,
              array.count > 0 else {
            throw SomeError
        }

~~~
saagarjha
A somewhat stupid way to solve this issue (of what is likely poorly-designed
API, given what you're trying to do here; optional Arrays are generally a code
smell) is to abuse the nil coalescing operator:

    
    
      guard !(obj.someArray?.isEmpty ?? true)

~~~
zapzupnz
Well sure, except if the array is optional (and I agree it's code smell, but
that's what you get when you use other peoples' libraries, I guess) that
statement doesn't unwrap the array for me to use; I'll either need to do it
manually on a second line (waste of effort) or every time I try accessing that
variable. If I access it a lot, this is inefficient duplication.

Plus, I don't like abusing the nil coalescing operator. Once you're abusing
anything, you're adding signal to noise and making the intent of a statement
less clear than necessarily, I feel.

+1 for isEmpty, though. According to the docs, count iterates over collections
that don't conform to RandomAccessCollection, so best to avoid unnecessary
overhead by adopting good practice! Thanks for that.

~~~
saagarjha
In your specific example, it didn't look like you wanted to use that array, so
I thought I could save you a variable. If you are planning to use it, then by
all means bind it to a variable for reuse.

~~~
zapzupnz
What other use is there for a conditional let?

~~~
saagarjha
I thought your only use for the array was to check its count. Now that I think
about it, that was probably a stupid assumption.

------
karmakaze
For normal scalars any are fine and I can see the number line merit of the
post. Where I find much greater value is when dealing with points in time.
Write x.isBefore(y) rather than y.isAfter(x) especially in compound contions.

------
dang
Discussed at the time:
[https://news.ycombinator.com/item?id=11148903](https://news.ycombinator.com/item?id=11148903)

------
SilverSlash
Claiming you shouldn't use the greater than sign in conditionals because
sometimes it's confusing is going too far.

Also in python you can just do `if 5 < x < 10` :)

------
noobly
..but the greater than sign is still being used?

~~~
deathanatos
Where is the article using a >, aside from examples of what it is advocating
against?

~~~
noobly
is there really a naming distinction between ‘>’ and ‘<‘? Is only one really
_the_ ‘greater’ than sign? Interesting if so! I always assumed it was context
dependent (i.e x < 10 could be said 10 is greater than x, so it’s still acting
as a greater than sign - but I see why I’m probably wrong here). I was
interested in seeing an arguement like another poster made, where notation be
like x = [0,1] might be proposed.

~~~
deathanatos
If you read

    
    
      Pull the lever when x < 0
    

aloud, you must read it as "Pull the lever when x is less than zero." Thus,
"<" is "less than", and ">" is "greater than", for that reason specifically.

Also, Unicode calls it U+003C LESS-THAN SIGN and U+003E GREATER-THAN SIGN.

At least, that's the terms that the article is using, and I think there's
sufficient context to identify that, and go along w/ it.

~~~
noobly
Well, and I don’t mean to be strictly pebdabtic, but you could read it as
“when 0 is greater than x”, but of course it takes more overhead and I see why
I was wrong. Thanks, it’s getting late today so I’m glad I managed to learn
something before the days up.

