in reply to Avoiding the == blues

I really really don't like:
if ( 0 == $foo )
There's just something wrong with it to me. I usually catch these bugs with proper unit testing.

Replies are listed 'Best First'.
Re^2: Avoiding the == blues
by TimToady (Parson) on Dec 31, 2004 at 18:12 UTC
    Yes, what's really going on here is that, while the computer treats $a == $b as commutative, the human brain is linguistically wired, and tends to parse such constructs asymmetrically as a topic and a predicate. And as it happens, the topic likes to be first. For similar reasons most OO programmers will choose to write:
    foo.equals(0)
    rather than:
    0.equals(foo)
    Despite the fact that Ruby considers 0 to be a Real Object, I suspect that even Ruby programmers will prefer the first form to the second, because that's how our brains are wired.

    The solution to all this in Perl 6 will be that assignment to an existing variable in boolean context will produce a warning under strictures, but assignment to a my declaration will not. The typical use for assignment in a boolean context is actually not the if statement but the while statement:

    while $item = shift(@foo) {...}
    and in most cases this is probably better written as:
    while my $item = shift(@foo) {...}
    or even better:
    for @foo -> $item {...}
    Likewise,
    if $x = long_expression() {...}
    can turn into
    given long_expression -> $x {...}
    I suppose we might also allow the gcc-like workaround of putting extra parens when you want to hide the assignment from the boolean context.
      Depends on the developer. It's better to write literal comparisons (literal the noun) as "bob".equals(someVariable), when there is a chance that someVariable could be null/nil/undef. Sorta the take on the if(someLiteral == someVariable) in c, so you couldn't write things like if(0=variable) by accident. Compiler err and all...
        >>"Put the constant on the left," he repeated. "You can't assign to a constant, so it's a syntax error if you say = instead of ==." Interesting, but I have to say that with practice an alarm bell goes off when I write such conditional statement anyway. In the same way that an alarm bell woulld need to go off in order to remember to put the constant on the left.
Re^2: Avoiding the == blues
by aquarium (Curate) on Dec 31, 2004 at 14:27 UTC
    i don't see your point....what is your point, about not liking it? Seriously though, I think that too many programming teachers actually teach the "$foo == 0" way, which gets ingrained in a lot of us. if you think of the equality test as a weight scale, with each variable/constant being a weight, it should make it fit better for you. you can also have some fun with short circuit logic:
    if ( 5 == $foo) print "tadaa";
    can become
    ( $foo -5) && print "tadaa";
    so you don't use == at all
    the hardest line to type correctly is: stty erase ^H