The elegance of optimised syntax
The following is an article I wrote on Medium back in September 2014. I just discovered it again and liked it so I thought I'd 'reprint' it here.
While staring at some code recently (code that wasn’t working) I was struck by how my code has improved over time by simple changes of syntax. As an example I’ll use toggling the value of a boolean variable: myvar
For those that don’t know a boolean value can only be either true or false. Some languages also permit the use of 1 or 0.
So when I first started out I would have explicitly compared the value to true in an if statement. If the variable is true, set it to false. Otherwise, set it to true:
if(myvar === true){
myvar = false;
} else {
myvar = true;
}
After learning that anything other than a ‘falsey’ value always equates to true I omitted the explicit comparison:
if(myvar){
myvar = false;
} else {
myvar = true;
}
An embarrassingly long time went by before I discovered the ternary operator making simple conditional assigns very concise:
myvar = (myvar) ? false : true;
I thought this was as elegant as it could get. A single line, a single declaration of the variable to be assigned and the two options separated by simple punctuation.
However, the application of simple logic and the use of the not operator (!) can make the original five line, forty-seven character if statement in to a single line, thirteen character piece of poetry:
myvar = !myvar;
In case this doesn’t make sense to you, it sets the variable to whatever it is not. So if myvar
is true it becomes not true, or false. If false it becomes not false, or true.
Each code block above does exactly the same thing and probably has similar performance impact. Yet the effect it has on code readability and source code file size are surely significant.