

Why are shortcuts like x += y considered good practice? - anacleto
http://programmers.stackexchange.com/questions/134118/why-are-shortcuts-like-x-y-considered-good-practice

======
jones1618
I agree with someone's DRY (Don't Repeat Yourself) answer but the benefits go
beyond reducing typing. In this case, not repeating the target variable
improves readability and avoids errors. Consider if you were coding this:

fruitx = fruitx + 23;

What if you also had a fruity variable and accidentally wrote:

fruitx = fruity + 23;

You (and the compiler!) might easily miss the difference.

Of course, there's a tradeoff with terseness vs. readability and some
languages (Perl, Lisp, APL) are notorious for having obscure single-character
shortcuts and chaining semantics that make them powerful and as opaque as
alien hieroglyphics.

It is always better to err on the side of readability and only use shortcuts
(like +=) that are easily understood by junior developers. If understanding
your code depends on obscure language trivia you'd only encounter in a devious
coding interview, you're only creating puzzles for your colleagues or your
future self to unravel later.

~~~
jack9
> not repeating the target variable improves readability and avoids errors

The reasoning was to replace an idiom as an incremental change for convenience
(for loops, as an example). It's possible to write x = 3+x but the idiom IS x
= x+3 for readability. The reason we continue to see it in languages, is
mimicry. There's no specific evidence that it's a good idea one way or the
other.

~~~
jones1618
I'm not sure I follow you. What "evidence" are you looking for? By reason and
experience, the idiom x = x + 3 is better than x = 3 + x precisely because it
puts the x's close together. x += 3 is even better because, as I said before,
it helps you avoid typos like x = y + 3.

Another example for C-like languages: Writing "if ( 0 == foo ) ..." is an
almost mandatory idiom because it is all too easy to write "if ( foo = 0 )
..." which the compiler will happily compile into useless code. Programming
languages are powerful weapons. Idioms just keep you from shooting yourself in
the foot with them.

------
informatimago
They are obviously not considered good practice. The proof: they don't exist
in Wirth's languages (Pascal, Modula-2, Oberon).

Wirth, Ichbiah and Meyer define good practice, not Kernighan, Ritchie, or
Thompson, and much less Stroustrup.

------
Someone
Because they allow some DRY. Compare

    
    
      x->y[z] = 42 + x->y[z];
    

with

    
    
      x->y[z] += 42;
    

And, historically, because it is a huge improvement on the erparlier

    
    
      x->y[z] =+ 42;

