5 ms·
Even if you made if/else an expression, the ternary is still useful for brevity. Compare: foo(a ? b : c) Versus: foo(if a then b else c end) Which do y
by charliesome 14y ago
Even if you made if/else an expression, the ternary is still useful for brevity.
Compare:
foo(a ? b : c)
Versus:
foo(if a then b else c end)
Which do you think reads more clearly?
- ori_b 14y agoThe slightly less terse: if(a) foo(b) else foo(c)
- qu4z-2 14y agoMy only complaint with that version is that foo() is repeated now. It's not clear at a glance that you're definitely calling foo, and only deciding which argument to pass. (Well, in this simple case it's quite obvious, but...)
- zackelan 14y agoIf that's really a concern: if (a): arg = b else: arg = c foo(arg) In my experience, trying to optimize for brevity at the expense of clarity is almost always a bad idea.
- tomlu 14y agoI like this - idiomatic, brief and clear: arg = a and b or c foo(arg)
- capisce 14y agoPersonally I don't really see what's unclear about foo(a ? b : c) In fact, I'd say your "trick" with using boolean operators on non-booleans that way is less readable.
- tomlu 14y agoI don't think there is anything at all unclear about (a ? b : c). I use it all the time when programming in C and its derivatives. The (a and b or c) idiom is used in Lua, Ruby and Python (in descending order of idiomaticness). Since the person I was responding to seemed to be using syntax reminiscent of these languages, I thought I'd offer up this expression form as an alternative to resorting to statements.
- webreac 14y agoThey are trying to optimize for clarity. Too much verbosity reduces clarity. It is not easy to find the correct balance between concision and cryptic. Many factors have also to be taken into account: should the program be easy to read by beginners or can we assume an experienced reader.