• ZeoS (unregistered) in reply to kipthegreat
    kipthegreat:


    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...

    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>
  • (cs) in reply to UncleMidriff
    UncleMidriff:
    Anonymous:
    Which means we're better off with an if statement here. Oh well.

    Why? I still like the the ? better. I'd rather keep it as one statement to visually scan over instead of an if.



    I'd venture to guess the reason is because with an if statement, you don't have to do "cnt == 1" twice.  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.


    That sounds preferable to temporary variables.
  • (cs) in reply to kipthegreat
    kipthegreat:


    Not really related to the WTF at all, but something I've been wondering:  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."

    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...


    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

    string test = null;
    System.Console.WriteLine("test = {0}", test ?? "{null value}");


  • (cs) in reply to a name
    Anonymous:
    I'd venture to guess the reason is because with an if statement, you don't have to do "cnt == 1" twice. 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.

    Have you ever looked at the code needed to implement printf? A double comparison of integers is the least of your worries.

    Not to mention we are either talking file IO (glaciers move faster), or interactive (the user will never notice the 2 processor cycles you saved)



    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.
  • (cs) in reply to Cloak
    Anonymous:
    Turnary operators can be pretty useful though.

    printf("There is %d %s of foo\n", cnt, ((cnt == 1) ? "instance" : "instances"));

    Without:

    if (cnt==1)
       printf("There is 1 instance of foo\n");
    else
       printf("There is %d instances of foo\n", cnt);

    Is that really that unmaintainable?


    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

  • neuro (unregistered) in reply to ZeoS
    Anonymous:
    kipthegreat:


    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...

    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>


    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
  • (cs)

     

  • (cs)

     

  • (cs) in reply to a name
    Anonymous:
    Which means we're better off with an if statement here. Oh well.

    Why? I still like the the ? better. I'd rather keep it as one statement to visually scan over instead of an if.



    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.
  • (cs) in reply to rogthefrog
    rogthefrog:
    rogthefrog:
    Anonymous:

    Turnary operators can be pretty useful though.

    printf("There is %d %s of foo\n", cnt, ((cnt == 1) ? "instance" : "instances"));

    Without:

    if (cnt==1)

       printf("There is 1 instance of foo\n");

    else

       printf("There is %d instances of foo\n", cnt);

     

    Is that really that unmaintainable?



    I'd factor everything out that can be factored out, though, like so:

    printf("There is %d instance%s of foo\n", cnt, ((cnt == 1) ? "" : "s"));




    Actually, if we're going down that road:

    printf("There %s %d instance%s of foo\n", (cnt == 1 ? "is" : "are"), cnt, (cnt == 1 ? "" : "s"));

    Which means we're better off with an if statement here. Oh well.


    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

  • (cs) in reply to rogthefrog
    rogthefrog:
    Anonymous:
    Which means we're better off with an if statement here. Oh well.

    Why? I still like the the ? better. I'd rather keep it as one statement to visually scan over instead of an if.


    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.

    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.
  • (cs) in reply to foxyshadis
    foxyshadis:

    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.


    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?
  • (cs) in reply to Stan Rogers

     

  • (cs) in reply to Stan Rogers
    Stan Rogers:
    foxyshadis:

    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.


    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?

    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.)
  • (cs) in reply to ComputerGuyCJ
    ComputerGuyCJ:
    Stan Rogers:
    it couldn't have been for the challenge of defeating the system

    True. I just got bored with all the nerds on this site and their stupid comments. I thought it much more entertaining to see humping hyenas and a camel's balls.

    You thought wrong.
  • (cs) in reply to kipthegreat

    kipthegreat:
    Not really related to the WTF at all, but something I've been wondering:  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."

    <FONT size=1>$actionType = $hasSiblings ? "cont" : "end";</FONT>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...

    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?

  • Dnal Rob (unregistered) in reply to JohnO

    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....

  • (cs)

    fuck me. these ppl are actually "programming".

    god has obviously forsaken me (money wise)

  • D (unregistered) in reply to kipthegreat

    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.

  • (cs) in reply to Jehos
    Jehos:
    ComputerGuyCJ:
    Stan Rogers:
    it couldn't have been for the challenge of defeating the system

    True. I just got bored with all the nerds on this site and their stupid comments. I thought it much more entertaining to see humping hyenas and a camel's balls.

    You thought wrong.

    Quite.
  • (cs) in reply to D

    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.

  • Your Name: (unregistered) in reply to kipthegreat
    kipthegreat:
    Alex Papadimoulis:

    In yesterday's post (Doing What You Say, Saying What You Do), we all learned how important it is to be explicit when naming functions; preferably, one should encapsulate the entire function's logic into that function's name. Although I didn't cover commenting in yesterday's post, the same rule should apply: be as explicit as possible. The ideal comments are free of any non-programming languages (English, Dutch, etc) and should be as verbatim to the code as possible. Nick F demonstrates this perfectly with code from (what I would imagine is) the set_actionType_to_cont_or_end_depending_on_whether_hasSiblings_is_true_or_false() function ...

    <font color="#006600">// if hasSiblings, actionType == cont; else actionType == end.</font>
    <font color="#000099">if</font> ($hasSiblings)
    {
    $actionType = <font color="#990000">"cont"</font>;
    }
    <font color="#000099">else</font>
    {
    $actionType = <font color="#990000">"end"</font>;
    }


    Not really related to the WTF at all, but something I've been wondering:  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."

    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...


    Gawd forbid we waste space, there's only so much of it available
  • (cs) in reply to ZeoS
    ZeoS:
      that code will be readable for any programmer...


    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
  • (cs)

    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);

     

  • Paul O (unregistered) in reply to kipthegreat

    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.

  • ZeoS (unregistered) in reply to dpm
    dpm:
    ZeoS:
      that code will be readable for any programmer...


    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


    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.

  • (cs) in reply to rbrendler

    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.

  • (cs) in reply to Boojum
    Anonymous:

    Sheesh. Haven't you people ever done anything in functional languages?



    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...

  • Z (unregistered) in reply to a name
    Anonymous:
    I'd venture to guess the reason is because with an if statement, you don't have to do "cnt == 1" twice. 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.

    Have you ever looked at the code needed to implement printf? A double comparison of integers is the least of your worries.

    Not to mention we are either talking file IO (glaciers move faster), or interactive (the user will never notice the 2 processor cycles you saved)



    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.
  • Z (unregistered) in reply to D
    Anonymous:

    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.


    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)


  • (cs) in reply to rbrendler
    Anonymous:

    Ternary is indeed a wonderful thing (although <FONT style="BACKGROUND-COLOR: #ffffff">there</FONT> is a special corner of hell for people who nest ternary ops), but one thing that I have seen bite the unwary is order of operations.  For example, in C++:

    std::cout << 1 ? 2 : 3 ;

    will output "1"!  Order of operations means that the << operator will be evaluated before the ?:, so this is the same as saying:

    (std::cout << 1) ? 2 : 3 ;

    Counterintuitive at best...

    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

  • Rain Dog (unregistered) in reply to kipthegreat
    kipthegreat:
    Alex Papadimoulis:

    In yesterday's post (Doing What You Say, Saying What You Do), we all learned how important it is to be explicit when naming functions; preferably, one should encapsulate the entire function's logic into that function's name. Although I didn't cover commenting in yesterday's post, the same rule should apply: be as explicit as possible. The ideal comments are free of any non-programming languages (English, Dutch, etc) and should be as verbatim to the code as possible. Nick F demonstrates this perfectly with code from (what I would imagine is) the set_actionType_to_cont_or_end_depending_on_whether_hasSiblings_is_true_or_false() function ...

    <font color="#006600">// if hasSiblings, actionType == cont; else actionType == end.</font>
    <font color="#000099">if</font> ($hasSiblings)
    {
    $actionType = <font color="#990000">"cont"</font>;
    }
    <font color="#000099">else</font>
    {
    $actionType = <font color="#990000">"end"</font>;
    }


    Not really related to the WTF at all, but something I've been wondering:  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."

    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...


    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.
  • mjc (unregistered) in reply to kipthegreat

    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.


  • (cs) in reply to kipthegreat
    kipthegreat:
    Alex Papadimoulis:

    In yesterday's post (Doing What You Say, Saying What You Do), we all learned how important it is to be explicit when naming functions; preferably, one should encapsulate the entire function's logic into that function's name. Although I didn't cover commenting in yesterday's post, the same rule should apply: be as explicit as possible. The ideal comments are free of any non-programming languages (English, Dutch, etc) and should be as verbatim to the code as possible. Nick F demonstrates this perfectly with code from (what I would imagine is) the set_actionType_to_cont_or_end_depending_on_whether_hasSiblings_is_true_or_false() function ...

    <font color="#006600">// if hasSiblings, actionType == cont; else actionType == end.</font>
    <font color="#000099">if</font> ($hasSiblings)
    {
    $actionType = <font color="#990000">"cont"</font>;
    }
    <font color="#000099">else</font>
    {
    $actionType = <font color="#990000">"end"</font>;
    }


    Not really related to the WTF at all, but something I've been wondering:  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."

    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...


    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. ;)

  • (cs) in reply to Maurits
    Maurits:
    Anonymous:
    Another thing: there are things you can't do without the ternary operator in some languages (like, say, C++):

       const int someVar = someCondition ? value1 : value2;

    Try and do that using ifs.  Maybe with some truly wretched casting it would be possible, but at that point, you're very clearly much better off just using the ternary operator.


    int tempVar = 0;

    if (someCondition) { tempVar = value1; } else { tempVar = value2; }

    const int someVar = tempVar;

    Gee, those three lines are just like, you know, sooo much easier to grok that the single line. Not.
  • (cs) in reply to Satanicpuppy
    Satanicpuppy:
    kipthegreat:

    Not really related to the WTF at all, but something I've been wondering:  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."

    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...


    I usually try and stay away from it because people who come along later always make the same grunting puzzled sound when they see it "Uhhaarooo?" and I have to explain it's just another way of writing a conditional, but the little crease between their eyebrows never goes away, and I know as soon as I'm not looking, that line will be replaced with if-then-else.


    I am glad that all of my colleagues are programmers and not script kiddies.
  • (cs) in reply to mjc
    Anonymous:
    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 \
         ? (n < 2 \
            ? p \
            : (q/r) \
            ) \
         : sqrt(2) \
        );

    I like this style - you might hate it.




    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.
  • flux (unregistered)

    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.)

  • (cs) in reply to dhromed

    "if supports" >> "if CASE supports"

    hmkay

  • Martin Vilcans (unregistered) in reply to rogthefrog
    rogthefrog:

    I'd factor everything out that can be factored out, though, like so:

    printf("There is %d instance%s of foo\n", cnt, ((cnt == 1) ? "" : "s"));




    Have fun localizing that code!

  • a name (unregistered) in reply to dhromed
    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?)

    Try this:
    (somecondition ? statementA1, statementA2 : statementB1);

    Disclaimer: I take no responsibility for what you or others might do with this knowledge.
  • (cs) in reply to Dnal Rob

    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.   

  • (cs) in reply to Maurits
    Maurits:
    Anonymous:
    Another thing: there are things you can't do without the ternary operator in some languages (like, say, C++):

       const int someVar = someCondition ? value1 : value2;

    Try and do that using ifs.  Maybe with some truly wretched casting it would be possible, but at that point, you're very clearly much better off just using the ternary operator.


    int tempVar = 0;

    if (someCondition) { tempVar = value1; } else { tempVar = value2; }

    const int someVar = tempVar;

    Failed for losing the constness

    Anonymous:
    kipthegreat:


    <font size="1">$actionType = $hasSiblings ? "cont" : "end";</font>

    That is much easier and doesn't waste so much space, and I don't see how it would be hard to understand...

    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?

    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).

    Anonymous:
    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 \
         ? (n < 2 \
            ? p \
            : (q/r) \
            ) \
         : sqrt(2) \
        );

    I like this style - you might hate it.


    This furiously looks like Lisp code with random crap thrown in.

  • Steve Bennett (unregistered)

    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...

  • (cs) in reply to ZeoS
    ZeoS:
    dpm:
    ZeoS:
      that code will be readable for any programmer...

    I don't want my code to be maintainable by "any" programmer.  {...}

    so... easy to read means dumb to you? 


    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

  • (cs) in reply to masklinn
    masklinn:
    Maurits:
    Anonymous:
    Another thing: there are things you can't do without the ternary operator in some languages (like, say, C++):

       const int someVar = someCondition ? value1 : value2;

    Try and do that using ifs.  Maybe with some truly wretched casting it would be possible, but at that point, you're very clearly much better off just using the ternary operator.


    int tempVar = 0;

    if (someCondition) { tempVar = value1; } else { tempVar = value2; }

    const int someVar = tempVar;

    Failed for losing the constness

    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?

  • Dnal Rob (unregistered) in reply to Syarzhuk
    Syarzhuk:

    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.   



    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.
  • (cs) in reply to Mung Kee

    Mung Kee:
    I'm sick of you and your homework.

    <FONT face="Courier New" size=2>you just sit there, and soon the chupacabra will attack you.</FONT>

  • (cs) in reply to mjc
    Anonymous:
    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 \
         ? (n < 2 \
            ? p \
            : (q/r) \
            ) \
         : sqrt(2) \
        );

    I like this style - you might hate it.




    I hope it's the forum software, because that's a bitch to read.
  • (cs) in reply to dpm
    dpm:
    ZeoS:
    dpm:
    ZeoS:
      that code will be readable for any programmer...

    I don't want my code to be maintainable by "any" programmer.  {...}

    so... easy to read means dumb to you? 


    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



    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.

Leave a comment on “Self-Documenting Comments”

Log In or post as a guest

Replying to comment #:

« Return to Article