views:

911

answers:

5

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


Duplicate:

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

+1  A: 

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.

Mehrdad Afshari
A: 

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.

JoshJordan
It's usually called the ternary operator because it's the only operator that takes three arguments.
Samuel
I'm talking about ? : operator (I always called it ternary operator: am I wrong?)
+1 for accuracy. Yes, it's called the conditional operator. It happens to be *a* ternary operator, but that only describes the number of operands, not its purpose/behaviour. If the C# team every introduces another ternary operator, people are really going to have to learn the right name...
Jon Skeet
Commenting ALL your conditionals? Really?
Jason Punyon
Yes, commenting all your conditionals. It is one thing to read through one logical flow of a method and find out what it does, but ascertaining WHY something happens is much harder, and that question comes up much more with conditionals.
JoshJordan
A: 

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.

Dustin Campbell
+2  A: 

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;
karim79
+2  A: 

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

Ted Dziuba