- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
it's very useful for filling java PreparedStatements, and that kind of things, but
"waste of space"? 2005! the problem of all those C abreviations where acceptable in 1980 where 1kb file was a lot, but now?
The thing is that you need to understand that languaje to read<font size="1">
</font>
<font size="1"> <font size="3">$actionType = $hasSiblings ? "cont" : "end"</font></font>
<font size="1"><font size="3">Isn`t it more clear to have
if(hasSiblings)
action=cont;
else
action=end;
</font></font>
<font size="1"><font size="3">? that code will be readable for any programmer...
</font></font>
<font size="1"><font size="3">
anyway, I love cond?res1:res2; :D
</font></font>
<font size="1"></font>
<font size="1"></font>
Admin
That sounds preferable to temporary variables.
Admin
No, you're not the only one - the ternary operator is very neat syntactic sugar. The only thing neater is C# 2.0's new null coalescing operator
Admin
Understood. That's why I said, " I've no idea if that'd make any difference in anything whatsoever, but it seems a wee bit silly to do two comparisons when you could get away with just one." There weren't any "OMG!!!! Thats so teh uneficientszorsz!!11!" kind of statements in my post because I agree with you that it will make a nearly imperceptible difference in performance, if any at all. That said, it still seems a bit silly to me, even if just from a personal preference standpoint, to use the same comparison twice when you could easily use it just once.
Admin
That maintained beautifully. (I corrected the error.) The other is a bit more involved.
if (cnt==1)
printf("There is 1 instance of foo\n");
else
printf("There are %d instances of foo\n", cnt);
The problem I see with ternary is people getting too cute. A simple assignment of alternatives is easy to read, but if the expressions get much more complex, it is difficult to parse them at a glance.
Sincerely,
Gene Wirchenko
Admin
you know, ternary is available in at least one language a -programmer- should be familiar with.
sure we don't count VB/Pascal-only kiddies as programmers, do we? (not implying that knowing VB/Pascal is bad thing itself, i know of at least one person who is a good programmer and yet writes mainly in VB) somebody like that should never ever touch any code, let alone some where you use ternary
Admin
Admin
Admin
We're better off with an if statement because there's only one evaluation. In the is/are + singular/plural version, the ternary operator would evaluate the same expression twice. It's a waste of time.
Admin
indeed, and you forgot the case when the instances are negative, remember the milliseconds converter?
so this would be best suited for a switch/case
Admin
I think the real problem is that repeating the conditional looks ugly and steals focus away from what actually gets done with it. (Since the eyes gravitate toward patterns so quickly.)
The reason ternaries sometimes get grouped with goto and their ilk is that some people, like the php wiz we had a week ago, enjoy putting an entire function's worth of code in a huge ternary statement that branches all different directions and turns the code into punctuation soup. In the same sense as ternaries can be sensibly used, gotos can be sensibly used (if only in C or classic VB, which both have abominable exception handling).
Aside:
OH FOR GOD'S SAKE don't tell me this forum software lets you post [/table] and all the other random html you want.
Admin
I'd believe that, but what I can't believe is that somebody has so little self-restraint that he feels it necessary to post crap like that. This site has never made any claims of running on an imperturbable platform, so it couldn't have been for the challenge of defeating the system. There is a word that describes people like that, but it eludes me at the moment. What is that bit of anatomy that is supposed to be like unto an opinion?
Admin
Admin
Yeah, I was just shocked. I forgot the other half of my exclamation, which was disbelief that there are no length limits to a post. I must admit I am still surprised after all this time by just how low the forum software can go!
Back on topic:
I forgot to say earlier, that AVIsynth (a script-host for processing video based on bash & loose C) has no if/then/else structure. Ternaries are the only way to branch code. (It processes up the script, rather than down (procedural), so that tons of time isn't spent unnecessarily filtering frames, so I can kind of see where they're coming from, but for the creation of complex in-script filters it leads to amazingly unreadable and unmaintainable code.)
Admin
You thought wrong.
Admin
I too am a fan of the ternary operator as long as they are not nested and the three expressions are relatively simple. You could argue that the ternary operator is superfluous (it is) and just provides an unnecessary option that can be abused. For example, if later you find that multiple assignments depend on the test expression will you be a good boy and replace the ternary operator with an if/else or will you be a lazy boy and add another ternary operator that performs the same test?
Admin
Meh, just today I wrote this in Delphi 6.
function IfElse(b: Boolean; t, f: Integer): Integer;
begin
if b then Result := t else Result := f;
end;
FOne := IfElse(anumber > somevalue, someothervalue; anothervalue);
FTwo := IfElse(anumber > somevalue, yetanothervalue, typingisbad);
I needed it to replace this:
if anumber > somevalue then
begin
FOne := someothervalue;
FTwo := anothervalue;
end
else
begin
FOne := yetanothervalue;
FTwo := typingisbad;
end;
or possibly
if anumber > somevalue then FOne := someothervalue else FOne := yetanothervalue;
if anumber > somevalue then FTwo := anothervalue else FTwo := typingisbad;
Maybe the third option is better....
Admin
fuck me. these ppl are actually "programming".
god has obviously forsaken me (money wise)
Admin
Am I the only one who likes the ternary ?: operator? It is usually grouped with global variables and goto statements as "bad no matter what."... I don't see how it would be hard to understand...
The order of the operators is a little confusing. Usually false is represented as 0 and true as 1. (Or rather, true as not 0.) So you might expect the false clause to come first, like the way you might write a switch statement, but it doesn't. That can be confusing to someone who's never seen it before.
It also reads backwards compared to an if statement.
(condition) if (true value) else (false value)
as opposed to
if (condition) (true value) else (false value)
or
switch (condition) { case first: (first value); case second: (second value); ...}
It's just ordered differently from anything else. I use it from time to time, but it just makes it that much harder for others to maintain.
Admin
Quite.
Admin
The ternary operator has it's place. If you get paid to code you should know when and where that is. If the concept is too much to grasp... here's a mop, go clean the bathroom.
Admin
Gawd forbid we waste space, there's only so much of it available
Admin
I don't want my code to be maintainable by "any" programmer.
Of course, any half-wit can quote me out of context to make it sound like I'm clinging to job security,
whereas I simply have pride in my work. I don't make my code more "clever" than it needs to be,
just like I don't make it any dumber than it needs to be.
ok
dpm
Admin
I prefer the tenary - ()? is just the postfix of if(), and ? means else. I don't see any "obfuscation" - just a way to write code faster. In fact, they should've designed C so that ?..: could completely replace if..else. Instead of
if(cnt==1) {
printf("There is 1 instance of foo\n");
} else {
printf("There are %d instances of foo\n",cnt);
}
use:
(cnt==1)? printf("There is 1 instance of foo\n")
: printf("There are %d instances of foo\n",cnt);
Admin
The Ternary operator has value when one prefers to write an entire if statement on a single line.
For example, if you are prone to write something like this:
if ($hasSiblings) {$actionType="cont"} else {$actionType="end"}
then you should consider the ternary operator to be your "friend". Because, after all, typing "?" and ":" and reducing the whole statement to a conditional assignment makes the code so much more readable.
/sarcasm
Sure, there may be times when you really want the statement to focus on the assignment, and not on the conditional. But you haven't really succeeded if you're using the ternary operator, have you: you've just embedded the conditional so that the assignment becomes less clear.
Optimization is what compiler groups are paid to look after. Don't try to do it all by compacting your code together.
Admin
so... easy to read means dumb to you? It sound like "if I don´t understand that, it has to be a brillant idea".
I don´t know why we like to do everything as difficult as we can even though there's an easier/more clear way to solve it.
Admin
Counterintuitive? Pfft. I consider the design decision to overload "bit shift" to mean "stream insertion/extraction" to be a WTF itself.
That's not the only operator that screws up because of the precedence level of "<<" and ">>".
The C++/STL designers should have simply invented a new overloadable operator for that kind of stuff, and made sure that it was at or near the end of the precedence chain.
While there are lots of choices, I tend to think that something like "~>" and "<~" reads much better is a lot easier on the eyes.
std::cin ~> x;
std::cout <~ x ? 0 : 1 <~ x << 2 <~ x >> 3;
Or, you know, just use functions and get it over with.
Admin
Like what? Scheme and CLisp have "if". Haskell has "if... then.... else". So does CAML, if I'm not mistaking. In all these languages, one normally formats the whole expression just like the corresponding C statement. And it's still not very readable (except in Haskell, which also has pattern matching, but that's a different story).
Some years ago, when I was still fresh to programming, I tried to design a language with no statements, using only the C operators. Can you guess what my imaginary code samples looked like? Luckily, it was only intended as a theoretical toy...
Admin
Also, the double test in printf("yada", (cnt==1?a:b), (cnt==1?c:d)) is extremly likely to be optimized away completetly by the compiler. Common subexpression elimination is one of the basic optimizations done by a compiler, since it saves a huge amount of computation when handling arrays for example.
Admin
The ternary operator isn't backwards, it just omits a different part than a standard C-if. The full form (which many of us read it as) is:
if (condition) then (true value) else (false value) end
The C-if leaves out the 'then'-part and the 'end'-part, i.e.:
if (condition) (true value) else (false value)
The ternary operator, OTOH, leaves out the 'if'-part and the 'end'-part, i.e.:
(condition) then (true value) else (false value)
Admin
Oddly, though I don't use ternary routinely (I'm afraid I would totally lose some of my coworkers if I did), I never had this problem. For some reason I've always typed: (x ? y : z). Always with parenthesis. Wasn't really aware you could do without them [:D]
Drak
Admin
The ternary operator has a lot of problems in that in some cases it adds bugs due to misuse and it also adds complexity to code, while it may be more concise to use it, it does not always produce more understandable code.
For more reference, look at the book Code Complete for a better discussion.
Admin
I really like the "?:" operator. I sometimes (especially with printfs in awk) nest it 2 or 3 deep. This would be hard to understand, except I indent it just like if-then-else.
An example (using awk's "" to indicate continuation line follows - not needed in C):
i = (j > k <br> ? (n < 2 <br> ? p <br> : (q/r) <br> ) <br> : sqrt(2) <br> );
I like this style - you might hate it.
Admin
I liberally pepper all my code and "sanitize" others code to use the ternary operator. I'm waiting the day when it will be forbidden by company policy.
Seems that some of my colleagues have trouble deciphering nested ternary operations. ;)
Admin
Gee, those three lines are just like, you know, sooo much easier to grok that the single line. Not.
Admin
I am glad that all of my colleagues are programmers and not script kiddies.
Admin
Indenting it like a verbose IF makes the whole deal less readable and completely defeats the quick-n-[dirty|clean] purpose of the ternary.
Your little patchwork of code there is not even slightly maintainable except by yourself.
If you need to nest conditions, use a verbose if.
I only use ternaries for assignment, or for "inline ifs" when inside a string, eg "blablabla " + (foo? "plup":"knork") + "blablabla".
Using ternaries as though they were normal ifs is
A) impossible to use fully, since ternaries only allow 1 statement per condition, while verbose ifs support {code blocks}. (granted, something that can be remedied by changing the language design. case: if supports multple statements without a codeblock, then why not a ternary?)
B) garbles up the code like a complex regex. See the post on the AVI scripting language some posts above.
Admin
Actual (well, slightly altered) usages of the ?:-operator from my code:
return a_side == BBT_LEFT ? a_node->left : a_node->right;
int max(int a, int b) { return (a > b) ? a : b; }
format_printf(a_format, "connected: %s\n", a_device->connected ? "yes" : "no");
format_printf(a_format,
"total, average : %d, %d\n",
a_device->count,
a_device->eventCount ?
a_device->count / a_device->eventCount :
0);
..and I do honestly believe the alternative of rewriting these as ifs does not increase the readability or maintainability of the code, but infact would do the reverse.
I could easily use 'if' instead if it were functional, that is, it could actually be an expression that returned a value, even if it were more verbose. if (eventCount) count / eventCount else 0 would be fine for me.
(As it is, I rarely use ?: in expressions that have side effects.)
Admin
"if supports" >> "if CASE supports"
hmkay
Admin
Have fun localizing that code!
Admin
Try this:
Disclaimer: I take no responsibility for what you or others might do with this knowledge.(somecondition ? statementA1, statementA2 : statementB1);
Admin
FOne := IfElse(anumber > somevalue, someothervalue; anothervalue);
FTwo := IfElse(anumber > somevalue, yetanothervalue, typingisbad);
This looks not much readable, plus the condition is evaluated twice
I needed it to replace this:
if anumber > somevalue then
begin
FOne := someothervalue;
FTwo := anothervalue;
end
else
begin
FOne := yetanothervalue;
FTwo := typingisbad;
end;
This is VERY readable. Also, if you get paid by the line of code, this style increases your paycheck.
if anumber > somevalue then FOne := someothervalue else FOne := yetanothervalue;
if anumber > somevalue then FTwo := anothervalue else FTwo := typingisbad;
This is a bit better than the first option, but I'd still vote fore 2nd. After all, can you be sure years later they wouldn't throw yet another option so you'd need to add FThree as well? I think one IF makes it so much easier to read and understand. Doing extra comparisons violates the DRY principle, in short - if you ever need to change the condition there would be a nonzero probability of you remembering to change it in one place but not another.
Admin
Failed for losing the constness
And yet they're being added to languages every day.
AFAIK, one of the next versions of Python will have a ternary operator (current 2.4.2 doesn't).
This furiously looks like Lisp code with random crap thrown in.
Admin
At the risk of defending this code, stuff like that can arise when you transform pseudo-code into real code. You leave the comments there to demonstrate that all the pseudo-code was definitely turned into real code, and obviously you can quickly check that it was done properly. I don't know how long you'd leave it there though...
Admin
You said "readable by any programmer". Now you say "easy to read".
Try staying in place when you're making an argument, eh?
ok
dpm
Admin
And I failed for missing a line...
Well, can I try "Failed for managing to be less readable, with more redundancy and more error prone than original" then?
Admin
Well, an important thing to remember is we're not programming for 10 MHz 80286s anymore. Evaluating the condition more than once is not going to hurt performance. On top of that, Borland writes VERY good optimizing compilers. I haven't checked, but I think they would optimize the second check away. And in this case, the values to assign are not function results which may or may not have side effects, these are just, well, variables.
I haven't heard of the DRY principle*, but the assignment of FOne is right next to FTwo. So updating one and not the other would only happen if I decided to smoke some crack before adding the third assignment. Which I never do.
So for me the most import thing is pleasing the eye, as technically the three versions are equivalent (apart from like 10 processor cycles). I know my eye likes not seeing begin/end pairs or 10 lines of code for 2 conditional assignments.
*So I googled. It's Don't Repeat Yourself. Ok. Like I said, the instances of this repetition are right next to eachother. Should it become problematic, you could assign the condition to a Boolean on the stack.
Admin
<FONT face="Courier New" size=2>you just sit there, and soon the chupacabra will attack you.</FONT>
Admin
I hope it's the forum software, because that's a bitch to read.
Admin
I would think that if X is "easy to read," and since that phrase doesn't specify or exclude any particular group for whom X is easy to read, then X would be "easy to read" by "any programmer." In other words, if X is "easy to read," that includes X being "readable by any programmer." "Easy to read" seems to be more general than "readable by any programmer" to me. Therefore, even if we can't say that ZeoS has stayed in one place while making his argument, all we can say is that he's moved to a more extreme version of his previous argument. He hasn't moved in closer to your position in an attempt to make his original argument seem more reasonable, which is what, it appears to me, you're accusing him of doing.
Of course, it's still early yet and I'm not fully awake, so I very well may be totally incorrect.