29
When is a shortcut appropriate?
Yesterday I saw this “pro” tip on LinkedIn:
In JavaScript, instead of Math.floor
use ~~
.
Fortunately, the majority of commentors on this “tip” pointed out that it would hurt readability.
A few brave souls tried to defend this syntactic sugar. I want to break down what I see as the pros and cons of shortcuts like this, to see if there are situations when it makes sense.
Reasons to use short cuts in code:
And in contrast, reasons not to use short cuts in code:
And a bonus just for this situation:
~~
isn’t actually equivalent to Math.floor
. I’ll let StackOverflow explain.So when do the pros outweigh the cons?
In my personal opinion, the only time less typing is more important than readability is on the command line. I.e. when typing bash commands that nobody else will ever read.
As soon as I’m writing a script or a program, future readability (even by me) wins over keystroke count by a mile.
In the case of performance-enhancing shortcuts, I use those only sparingly, in areas of code that are truly performance critical. And in such cases, I probably use a comment to explain why I chose a less readable form in that instance.
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
— Martin Fowler
1Although auto-complete in most IDEs can mitigate or entirely eliminate this benefit.
2In reality the savings are likely to be less, or nothing, with the use of on-disk and over-the-wire encryption.
3But this one does not
2In reality the savings are likely to be less, or nothing, with the use of on-disk and over-the-wire encryption.
3But this one does not
If you enjoyed this message, subscribe to The Daily Commit to get future messages to your inbox.
29