Mr. Ternary is greater than Mrs. If Else

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PerlPhi
    New Member
    • May 2007
    • 5

    Mr. Ternary is greater than Mrs. If Else

    hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma.

    codes as follows using Mrs. If Else:

    [CODE=perl]#!perl/bin/perl

    use strict;

    print "Are you sure you want to quit ('yes' or any key for 'no'): ";
    chomp($_ = <STDIN>);

    if (/\byes\b/i) {
    print "Press any key to exit...";
    <STDIN>;
    exit;
    }
    else {
    print "Thanks, you stayed... But then, goodbye.\n";
    print "Press any key to proceed...\n";
    <STDIN>;
    }

    print "GOOD DAY";[/CODE]

    equivalent codes for Mr. Ternary as follows:

    [CODE=perl]#!perl/bin/perl

    use strict;

    print "Are you sure you want to quit ('yes' or any key for 'no'): ";
    chomp($_ = <STDIN>);

    /\byes\b/i ?
    eval {
    print "Press any key to exit...";
    <STDIN>;
    exit;
    }
    :
    eval {
    print "Thanks, you stayed... But then, goodbye.\n";
    print "Press any key to proceed...\n";
    <STDIN>;
    };

    print "GOOD DAY";[/CODE]

    Advantages of Mr. Ternary over Mrs. If Else:

    1. shorter code
    2. permits the parenthesis not to be used in the expression
    3. permits the curly braces not to be used (well in here, eval takes its place. and note if you put an eval over Mrs. If Else, then Mr. Ternary is more appropriate)
    4. promotes runtime error handling (the program doesn't exit so sudden)
    5. the statements are more clearer to understand after a true or false evaluation

    Disadvantages of Mr. Ternary:

    1. difficulty in reading (only for the first timers because this is not conventional)
    2. the return value of eval cannot be assigned to another variable (but there is the special variable $@ that holds it for you. you can evaluate that after the ternary operation)
    3. tedious in bullet proofing a program (it is because you cannot quickly notice the runtime error inputted by the end user or file. in which Mr. Ternary uses the eval. it happens when your statements are so lenghty inside the eval block. but here is a solution for that, see next)

    optional code revisions while bullet proofing:

    [CODE=perl]#!perl/bin/perl

    use strict;

    print "Are you sure you want to quit ('yes' or any key for 'no'): ";
    chomp($_ = <STDIN>);

    /\byes\b/i ?
    \& {
    print "Press any key to exit...";
    <STDIN>;
    exit;
    }
    :
    \& {
    print "Thanks, you stayed... But then, goodbye.\n";
    print "Press any key to proceed...\n";
    <STDIN>;
    };

    print "GOOD DAY";[/CODE]

    the only code was changed in here was "eval" to "\&"... now my delimma goes here... i don't know whats "\&" for. i just seen it on the Perl documentation under the strict pragma, and i read what it says "There is one exception to this rule...\& is allowed so that goto &$AUTOLOAD would not break under stricture.". well im just a novice programmer with Perl i don't really understand that. so what does "\&" mean?

    back to Mr. Ternary, i think there is just only one slight drawback in using the ternary operator. that is difficulty in reading. but then its easy to overcome. so in other words Mr. Ternary is more handy than Mrs. If Else. so i think Mrs. If Else should be dropped from our system.

    but then, if you have other downs in mind on Mr. Ternary, your statements will be gladly evaluated, then i will give you the output.

    thanks in advance... keep deep and dark!

    From: PerlPhi
    Last edited by miller; May 19 '07, 05:54 PM. Reason: Code Tag and ReFormatting
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Certainly eval has it's advantages. But what happens if someone enters:

    exec "shred --remove";

    into your eval blocks?

    Comment

    • PerlPhi
      New Member
      • May 2007
      • 5

      #3
      Originally posted by KevinADC
      Certainly eval has it's advantages. But what happens if someone enters:

      exec "shred --remove";

      into your eval blocks?
      well i tried that, but everything just happens so normal... well i think nothing well really go wrong if i inputted that on whatever <STDIN> i go... because i didn't used any value of <STDIN> except for pattern match only...

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        Actually you're correct. I didn't really take the time to look at your code. It is safe as it is.

        But.... your original question of why it seems the ternary operator is not used as much as you might think it could be, I am not sure why that is. My guess is that many perl programmers you come across on forums or in a class setting just never got used to using it or don't understand how to use it or have better alternatives. But also, your example of the ternary operator does not looks like less code/typing to me.

        Comment

        • miller
          Recognized Expert Top Contributor
          • Oct 2006
          • 1086

          #5
          Hello PerlPhi,

          A very amusing post. However, there are a few misconceptions from the very beginning.

          1) "i was wondering why do some programmers rarely uses the ternary operator"

          The primary reason why people don't use the ternary operator is lack of exposure. As in perl, there always more than one way to do things, and the ternary operator is one of those things that has obvious replacements, namely the if construct. It's generally not until people learn how to code modules and start examining more profession code that they learn about the ?: operator and how it can be used to make cleaner code.

          2) "wherein it is less typing indeed"

          It is less typing, but it's not THAT much less typing. The primary instance where it becomes obviously useful is when a variable is being initialized based off of some conditional. In this situation, you'll sometimes see beginning programmers do some type of if construct.

          [CODE=perl]
          my $var;
          if ("some condition") {
          $var = "value 1";
          } else {
          $var = "value 2";
          }
          [/CODE]

          In this case, the code can be simplified a lot and made more readable by using the ternary operator.

          [CODE=perl]
          my $var = "some condition" ? "value 1" : "value 2";
          [/CODE]

          There are lots of other instances where it's use is obviously beneficial, but I won't bother listing those.

          3) "i believe in the classic virtue of Perl which is laziness."

          Wrong.

          In no way should you consider this a perl virtue. This is a common stereotype of perl hackers. But perl programmers do not perscribe to this a characteristic.

          Just because there is more than one way to do it, does not mean that each way is equally prefered. There is often a single method that balances readability, maintainability , efficiency, assumed risk, all of the primary concerns of programming.

          Using the ternary operator in the way that you have demonstrated is not good. This is what the if construct is for.

          Conclusion)

          It's definitely entertaining to experiment with all the different ways that you can accomplish the same task in perl. But I encourage you to not use something simply because you can. Make sure there is a reason behind it. And hopefully a good reason. Making code 2 characters shorter is not a worthwhile endevour unless you're doing golfing. And that's never something that you should use for production code.

          Keep the interesting observations coming.

          - Miller

          Comment

          • prn
            Recognized Expert Contributor
            • Apr 2007
            • 254

            #6
            Originally posted by miller
            3) "i believe in the classic virtue of Perl which is laziness."

            Wrong.

            In no way should you consider this a perl virtue. This is a common stereotype of perl hackers. But perl programmers do not perscribe to this a characteristic.
            Let me say right off the bat that I generally agree with miller's points here, but I will point out the three "great virtues" of a programmer (from the Camel book, I have the 3rd edition in front of me, but I'm pretty sure it was in earlier editions too):

            Originally posted by Wall, Christiansen and Orwant
            Laziness
            The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer.

            Impatience
            The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least that pretend to. Hence, the second great virtue of a programmer.

            Hubris
            Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer.
            Now, of course these terms and descriptions were obviously selected with more than a bit of humor intended and the applications of the terms as Wall, Christiansen, Orwant and Schwartz (or whatever combination or subset of them came up with these) intended them are NOT the stereotypical applications of terms like "laziness", but properly understood, "laziness" is definitely a virtue. :)

            But miller is certainly right, too, that "laziness" is NOT a virtue if the word is interpreted to mean just saving a couple of keystrokes. There's always more than one way to do anything, but miller points out correctly that they are not simply interchangeable . There are also lots of reasons to make good choices among those different ways of doing things and saving one or two keystrokes is rarely a good reason. The ternary operator can clarify or it can obfuscate. Always strive for clarity! "Laziness" as a virtue requires a longer-term outlook, not just a narrow view.

            Paul

            Comment

            Working...