Ternary operator: bad or good practice? [duplicate

2019-01-26 03:26发布

问题:

I'm looking for reasons to use/not to use it and for original ideas (in their use and to replace them).


Duplicate:

  • To Ternary Or Not To Ternary

Related (but does not address the question being asked):

  • Which coding style you use for ternary operator?

回答1:

For the sake of readability, I only use a ternary if it fits into one 80-char line.



回答2:

Good for short tags in templating languages like PHP, e.g:

<form>
<input type='radio' name='gender' value='m' <?=($gender=='m')?"checked":""?>>Male
<input type='radio' name='gender' value='f' <?=($gender=='f')?"checked":""?>>Female
</form>

Good for switches in javascript/jQuery:

var el = $("#something");
$(el).is(':visible') ? $(el).hide("normal") : $(el).fadeIn("normal");

Good for assignment, especially where a particular variable name can take different types:

$var = ($foo->isFoo()) ? 'Success!' : false;


回答3:

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear. If the intent is not clear, it is best to use a temporary variable with a clear name whose value is assigned using an if-statement, or to use a function with a good name that returns the expected value.



回答4:

It's something like the for loop. Makes sense for what it's made for but when you try to stick more stuff in it, it becomes unreadable.



回答5:

Which ternary operator are you talking about?

A ternary operator is any operator that takes three arguments.

If you're talking about the ? : operator, this is called the conditional operator. I can't live without it anymore, personally. If-else statements look so messy to me, especially when doing a conditional assignment. Some complain that it looks messy, but it is still possible (especially if using Visual Studio or another intelligent-formatting IDE) to make things easily readable, and you should be commenting all your conditionals anyway.