I'm personally an advocate of the ternary operator: () ? : ; I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.
What are your feelings on it? What interesting code have you seen using it?
I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):
where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).
I don't mind it for small things like:
or even slightly tricky things like:
If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.
The only time i think ternary operators make code harder to understand is when you have more than 3 or 4 in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.
(Hack of the day)
Then you can do if-then-else as expression:
By the measure of cyclomatic complexity, the use of
if
statements or the ternary operator are equivalent. So by that measure, the answer is no, the complexity would be exactly the same as before.By other measures such as readability, maintainability, and DRY (Don't-Repeat-Yourself), either choice may prove better than the other.
Use it for simple expressions only:
Don't chain or nest ternary operators as it hard to read and confusing:
Moreover, when using ternary operator, consider formatting the code in a way that improve readability:
Only when:
$var = (simple > test ? simple_result_1 : simple_result_2);
KISS.