When is a shortcut appropriate?
The only time less typing is more important than readability is on the command line. When writing code, readability wins by a mile.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:
- It requires less typing1.
- Each use saves (up to2) 8 bytes on disk, in memory or over the network.
- Some shortcuts improve performance.3
- Short cuts may make you feel more “advanced” as a programmer.
And in contrast, reasons not to use short cuts in code:
- Fewer people will understand the code, as only those who know the shortcuts can read it.
- Even for those who understand the shortcuts, it often increases the cognitive load of reading code.
- Many shortcuts make searching the code harder.
And a bonus just for this situation:
~~
isn’t actually equivalent toMath.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