I’ve been told to not use ternary conditional operators (?:) unless necessary.
My question is, why?
I like to use the ternary operator when writing an if/else would only be one statement each. I think it looks easier to me and it’s easier to write.
Again, only if it’s really really short (1 line of if/else). I can understand why nested and multiple ternary are evil.
So what is the problem with this way of doing things? Is it all a matter of preference or are there performance costs?
Also, whenever I have more than 2 or 3 conditions for else or elseif, I usually use a switch statement. Is this good practice?
I see no problem (and have never heard of a problem) with the tertiary operator. In fact, it makes code more concise and, unless the reader is a beginner, more clear in my opinion.
Again,
switchis really just an abstraction and it’s more about the clarity. I use switch when I only rely on one variable. If you’re requiring extra checks inside each case that’s bad, but it seems like you’re already pretty conscious of these things.