Yoda Notation, I Use; Do You?
Enlisting Anastrophe In Our Code
I’ve worked at enough companies, with enough different development philosophies, that I can handle most coding convention quirks. While at Microsoft, my coding kept getting more and more whitespace: first, spaces between parentheses and, later, open braces on the next line. Four spaces, no tabs, has been a mainstay across most of my career, though finance folks favor two-space indentation, as if that results in more efficient code. Coding conventions are an infamous resource sink; Joel Spolsky’s article, Making Wrong Code Look Wrong, features an entertaining aside on the futility of negotiating coding conventions.
One especially divisive coding practice is one that I’ve adopted since the late 1990s, after I asked one of my developers (I was his manager) why he was writing the code that way. He’d written something like:
if ( NULL == wndptr )
which, to some developers, looks awkward because they expect the more complex expression to be on the left of the == operator.
The awkwardness led to the name Yoda Notation, after the odd word ordering in the Jedi Master’s speech. (And now’s as good a time as any to mention that there are articles arguing against use of Yoda notation, though this one brims with strawman energy.)
At the time, when I asked, Why lead with the 0? Why not put wndptr on the left?, my employee said, Well there’s a typo and I only put one equal sign in the expression, if 0 is on the left, the code won’t compile because it’s not an l-value. That’s an oft-cited reason that generally is no longer true – most compiler will catch that error – but I still tend to put the constants on the left side in such expressions for another reason. When I write:
if ( 0 == threadIdx.x ) {
it’s as much for dramatic effect as to guard against the possibility of typos.
It turns out there’s a name for the deliberate misordering of words for strategic effect: it’s a literary device known as anastrophe.
Another, less visible example (you’ll soon see why) of anastrophe that finds expression in my code is when I’m writing instrumentation that should never find its way into production code: I don’t indent it at all. Sometimes it stands out like a sore thumb – but that’s the point – I want it to stand out so it gets removed before getting pushed.
The final argument in favor of Yoda Notation is that you have to write the code somehow, so any additional information you can bake into the source code is useful.
Anyway, once my employee explained his reasoning, I embraced the idea and, left to my own devices, I use it most of the time. It’s a low-grade way to Write Code For The Next Guy. As with all coding conventions, rules are made to be broken and your mileage may vary! But if you have ever wondered why my code features Yoda Notation, now you know.

