Ternary operator: bad or good practice? [duplicate]

假如想象 提交于 2019-11-29 09:06:16

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

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;

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!