clojure-style-guide icon indicating copy to clipboard operation
clojure-style-guide copied to clipboard

Add section about Yoda conditions

Open camsaul opened this issue 3 years ago • 2 comments

Consider two ways to check what sort of bird we have on hand:

  1. (= bird-type :toucan) -- one reads this code as "bird type equals toucan"
  2. (= :toucan bird-type) -- you'd read this as "toucan equals bird type"

Now while they both do exactly the same thing, the former is the "normal" way to write things and the latter is a Yoda condition

camsaul avatar Jul 14 '22 18:07 camsaul

I don't find anything wrong with 2. and it has specific benefits in many languages because having the constant first avoids this error:

if ( x = 2 ) { ... } // assignment

if ( 2 = x ) { ... } // compiler will catch this as an error!

if ( 2 == x ) { ... } // what was actually intended

So you'll likely find a lot of people who've had that drummed into them for years and it'll be natural for them to write:

(if (= 2 x) ...)

(and I do this myself, very deliberately)

seancorfield avatar Jul 14 '22 18:07 seancorfield