Like any profession, programming is full of things you should do, and things you shouldn’t. Some of these are passed-down experiences, and some are momentary fashions.
One of the former is that you should write a conditional using Yoda notation.
That is, instead of writing:
if ( x == 1 )
You should write:
if ( 1 == x )
The reasoning being that it avoids unintentionally assigning a value:
if ( x = 1 )
This, according to The Wisdom, is the cause of such incredible bugs that we need to contort our brain to prevent it ever happening.
While I appreciate the desire to prevent bugs, in this instance it seems entirely unnecessary. In fact, I’d say that it’s positively detrimental.
You see, the code is written once.
It is read many, many, times, and each time you have to mentally reverse your natural tendency to think of
if x = 1 and make it become
if 1 = x.
Do you think like that? I don’t. It’s a lot of wasted effort.
Is this such a massive problem that it requires this kind of cognitive overhead?
In my entire programming career I’ve maybe made the assignment mistake once. It was easy to spot.
On top of that, we now have incredible linting tools that identify these situations. There is no reason to have an assignment inside a conditional anyway, and we can let our tools tells us this.
You should write your conditionals the way your brain reads them. The cognitive load happens once, when writing, not once every time it is read.
Yoda is clearly not a programmer. Each time I come across a Yoda conditional it costs me valuable seconds in which I could be trying to understand how Kirk is Yoda’s father’s brother’s sister.
Also, I immediately dislike the code. I don’t like code that I dislike.
Very very wrong is Yoda.
Leave a Reply