Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

What is the advantage of the C# ternary operator?

If you don't know what I mean here is an example:

http://weblogs.asp.net/dreilly/archive/2003/10/08/31166.aspx

I work with someone who uses this all the time and I find it to be incrediblely unreadable.  Maybe it is just that I am not used to it but since you can do the same thing with a nice if/else I am not sure I get the advantage. 

The author comments in the above link that it is compact and that to me is part of the problem.  It is so compact that you cannot put a break point on it in case, oh, I don't know, you are trying to debug it.  I am not sure that compact is worth it in this case.

So what am I missing?

Mark Flory
Friday, June 24, 2005

A proper education in computer science that includes functional languages, such as ML or Lisp?

The ternary operator is basically the C variant (it's inherited from C/C++, not a C# invention) of the Lisp cond operator.

The point is that you have a single expression that returns a value; you can specify it inline in a function call, for instance: My.Extremely.Lengthy.Method.Call.With.Very.Many.Namespaces(a == b ? a * 2 : a * 3).

You don't have to repeat the operation being performed in two if/else branches, and you don't have to define temporary variables.

Apart from that, it's aesthetics: anyone who had any exposure to functional programming will agree that the ternary operator is much prettier than the cumbersome if/else construct!

Chris Nahr
Friday, June 24, 2005

PS: But I would agree that it's not smart to use the ternary operator if the sub-expressions are so complex that you might want to put a breakpoint on them... in this case, an if/else block is probably a better choice.

Chris Nahr
Friday, June 24, 2005

I don't like the ternary ? because it's not obvious which end is which. In a classic "if" the true and false branches are easy to pick out. With ? I have to remind myself it reads the same as a classic if.

I have coded bugs with ? and I have debugged other people's bugs with ?.  Bad uses of ? are easy for me to overlook.  I've rarely coded a bad three-line if/else.

The intrusion of a little bit of the functional paradigm into a mostly sequential language is typical of the big-bucket model of language design. Throw a bunch of stuff into a big bucket and let everyone use what they want.  PL/I was a classic of this genre, so is C++.  C# actually reduces the size of the bucket, which is one point in its favor.

That said,
  return (condition) ? f1(x); f2(x);
can be the clearest way to write something.  Did you notice my syntax error? Back to point 1.

Henry Troup
Friday, June 24, 2005

You are probably right that I did not receive a proper education in such things.  I did at one time know a little LISP but since I never used it so I forgot it.  I do that because I am human.

I guess I should be ashamed though because I have spent a fair amount of time coding in C and I still didn't know what it was.  I must have skipped that chapter in Kernighan and Ritchie.

I will mark you down for pretty.

Thanks.

Mark Flory
Friday, June 24, 2005

I obviously agree with you Henry and was thinking that in a code review I would have someone change it just because the next guy maintaining the code might not have a proper education.

I was also thinking about my breakpoint that sometimes I cannot see the bug in code but have to see the value produced by the buggy code. 

I know, I know, it was right there to see and I should be able to add six to five in my head and know that something is wrong.  I should also be taller, thinner, and better looking.

Mark Flory
Friday, June 24, 2005

The ternary operator is banned in our shop. If-else is always used. It's more flexible, easier to maintain, and easier to read and understand. Why clutter the code with more than one syntax? Use if-else and quit arguing over "when it's appropriate" to use the ternary operator. All the time spent arguing over when to use an if-else vs. the ternary operator far outweighs any benefit it could possibly have.

Also, people who tell you that you didn't get a proper education because you don't understand it off hand are just idiots.

matt
Friday, June 24, 2005

"That said,
  return (condition) ? f1(x); f2(x);
can be the clearest way to write something.  Did you notice my syntax error? Back to point 1."

The compiler certainly will notice this error... in fact, a missing ":" after the "?" will be flagged by the Visual Studio editor, no need even to compile. So I'm not sure what your point is.

Getting the ?: right with the ternary operator is no different from getting the {} and nesting levels right with if/else blocks. If anything I'd say it's _easier_ to get right.

Chris Nahr
Friday, June 24, 2005

I doubt seriously that Chris is an idiot but he may not even realize that he came off kind of arrogant (at least to me).

He is right, in a sense, that I probably should have known what it was so that I could make a conscious decision to not use it.  Of course for all I know maybe I once did and have just forgotten about it.

Mark Flory
Friday, June 24, 2005

I did a little digging and in the book Inside C# they state that the resulting MSIL is "marginally smaller - though no more efficient".  Taking their word on it then it would seem that the likely argument is going to come down to coding style.

I probably shouldn't keep answering my own question but my other worry with this is that, although the initial code might be simple, it might gain some code barnicles through the years that make it difficult to decipher.

Mark Flory
Friday, June 24, 2005

"Also, people who tell you that you didn't get a proper education because you don't understand it off hand are just idiots."

Also, people who ban simple, common language constructs because of perceived maintenance difficulties are just mediocre code monkeys who should stick with VB...

The "proper education" quip was an ironic reply to the OP's final question, "What am I missing?" As it happens I haven't had _any_ exposure to functional languages in my CS study, so I didn't get a proper education either. But I did eventually play around with Lisp and Ocaml a little, and that's why I say the ?: operator is much easier to use and appreciate once you know where it's coming from. That has been my experience, anyway.

Another point on debugging: you can break up the operator on multiple lines. This closely simulates the cond syntax and allows placing breakpoints on the individual sub-expressions:

return (a == b ?
    VeryLongFirstExpression :
    VeryLongSecondExpression);

Chris Nahr
Friday, June 24, 2005

Um...Chris...isn't this an operator we are talking about.  Just because you break it up over seperate lines are you sure you can put a breakpoint on the seperate terms?

I would think at least in VS that it would breakpoint all of it.  What's more because you don't use temp variables you can know what is evaluated without doing it in your head.  At least as far as I know you cannot watch an expression.

I do agree that matt shouldn't have called you an idiot but on the other hand getting pissed off about it doesn't help.

Mark Flory
Friday, June 24, 2005

Hmm, I could've sworn you could put breakpoints on individual lines but I just tried in Whidbey, and you're right... the whole expression gets highlighted. You still can step into the various methods that might get called, of course, but you can't break directly on an expression branch. I submitted a feature suggestion in the Microsoft tracking system.

PS: I'm not pissed, I just didn't use smileys anywhere which was apparently a mistake. Sorry if anyone took any offense, that was just me being witty...

Chris Nahr
Friday, June 24, 2005

Cool.

Anyway, I understand your point of view.  I don't think I am going to start using it and I probably would point it out in a code review (which my current company doesn't do so the point is probably moot).

The guy who used it is not exactly my favorite person so maybe that has me jaded.  I suspect if you could see his code you wouldn't like it either but you would probably hate mine as well.

The only reason I brought this up is that I had to take a proficiency test on C# for a job and that was one of the questions.  I didn't know the term ternary operator, although I could parse what it meant, and did not relate it to what I knew as a conditional operator.  I only knew that because of the forementioned guy's code, and have still never felt the need to use it, and so I missed the question.

So I admit I was (well...am) ignorant and in some small way it cost me (not very much though because the test was otherwise pretty easy).

Mark Flory
Friday, June 24, 2005

"Also, people who ban simple, common language constructs because of perceived maintenance difficulties are just mediocre code monkeys who should stick with VB..."

I don't even know how to program in VB. ;)

We ban it for very good reasons. They are not "perceived maintenance difficulties". The ternary operator is great when the statements are small. But what happens down the road when the logic needs to be changed and what used to be one statement needs to become 10? Now you have to convert a ternary statement into an if-else. This is clearly a maintenance issue with increased risks over just writing it as an if-else to begin with.


BTW... you were the one who started the whole flame war by being so darn rude to the OP. We both read into it that you were telling him he was a poor programmer. And now you've done the same with me. Quite ridiculous if you ask me. But I promise not to be rude anymore. I have better things to do with my time.

matt
Friday, June 24, 2005

The ternary operator is not hard to convert to IF-ELSE.  What's the big deal?

By the same logic, do you force people to use IF-ELSE instead of SWITCH?  Or vice-versa?

As far as refactoring goes, ternary->IF-ELSE is nothing.

I think a much more sane approach is just to ban abuse of the ternary operator.  That means

1) No nested ternary operators
2) No using the ternary operator for flow control.
3) No using the ternary operator when the conditional part becomes complicated (i.e. anything that requires more than one boolean operator).

Richard P
Friday, June 24, 2005

I'm wondering if you also ban people from things like i++ because i = i + 1 is so much more readable and maintainable?  I mean, what if you need to change it to increment by 2??

SomeBody
Friday, June 24, 2005

Interesting that the blog posting mentions IIf.  The _only_ places I've ever used IIf in VB programming are where I couldn't use If...Then...Else for some reason.

One example is Access queries where you want to do different string joins based on whether a field is null or not.  IIf works for this, whereas you can't use If...Then...Else in Jet SQL.

But other than that exception, I don't see any advantage in using IIf...or in using the ternary operator.

Kyralessa
Friday, June 24, 2005

I just like using the ternary operator because it saves space.

Matt B
Saturday, June 25, 2005

Trust me. I've had this discussion at least a dozen times and the side that advocates the ternary operator never comes up with anything better than "it saves space" or "it is easy to understand, go back and get a better education". No one has ever been able to come up with a REALLY compelling argument for its use.

We ban it. That is just us. One of the big reasons is because it is easier than going through this whole heated debate every time we get some hard nosed programmer who thinks the rest of the world should bend to his every whim. Why have so many ways of doing the same thing? Pick one and standardize on it. No more discussion needed.

The fact that we ban it shouldn't keep you from enjoying using it. Just keep in mind that many shops will ban its use and for good reason. The OP is obviously an intelligent fellow. He wasn't that familiar with it. There is probably a good reason why many programmers would prefer to not use it. If you don't want to believe me, then take that as a sign.

Have a good weekend.

matt
Saturday, June 25, 2005

> I'm wondering if you also ban people from things like i++
> because i = i + 1 is so much more readable and
> maintainable?  I mean, what if you need to change it to
> increment by 2??

how about i+=2

Adam Tylmad
Saturday, June 25, 2005

" I'm wondering if you also ban people from things like i++
because i = i + 1 is so much more readable and
maintainable?  "

No, why would we? That wouldn't make sense.  ;)

matt
Saturday, June 25, 2005

Oh and by the way, no one has answered the original question posed by the OP: "What is the advantage of the C# ternary operator? "

In the dozens of times that I have had this argument, nobody can ever show a real advantage. It is always just a matter of preference. That is never enough to persuade our group against just banning it altogether.

matt
Saturday, June 25, 2005

Thinking about Richard's rules about using it it occurred to me that an easier rule might be to just NOT use the ternary operator.

I have to agree with Matt that there does not appear to be an advantage and it comes down to a question of style.  Since I believe a simple standard is usually more easily followed and enforced I would advocate dropping it.

Mark Flory
Sunday, June 26, 2005

> "What is the advantage of the C# ternary operator? "
It's terse

Joe
Monday, June 27, 2005

*  Recent Topics

*  Fog Creek Home