Hacker News new | ask | show | jobs
by jeddy3 1581 days ago

   x = bar()
   if val {
       x = foo()
   }

Is both shorter and functionally more equivalent with the ternary example.
3 comments

But you execute bar() when you don't need it. At best it's wasteful, at worst bar() actually is sendNuke().
I did think of this, but left it out of the original post to keep it shorter. It is functionally better, but in terms of reading code, I find it easier to keep initialization blocks together and linearly scoped; the optional branch means I have to actually figure out which branch is being taken. That's definitely in the personal preference area though

I'd still rather a ternary over any of the above options though!

Nope, that's incorrect. When val is true both functions are called.