4 ms·
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 r
by jones1618 11y ago
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 11y ago> 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 11y agoI'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.