• (cs) in reply to Master Rick
    Anonymous:
    I remember learning a rhyme about 'I before E except after C....' when I was about 6.

    My friend Sheila is particularly dismissive of that "rule", for some reason.  Weird.
  • (cs) in reply to tyler

    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.

     

    What about

    return (condition1(x) || !condition2(x) || condition3(x));

  • boicy (unregistered) in reply to emurphy
    emurphy:
    VGR:

    private boolean isAdministrator(String authCode)
    {
        return "01".equals(authCode);
    }

    private boolean isFurniture(String productCode)
    {
        return "004".equals(productCode) || "005".equals(productCode);
    }


    Is there a good reason to avoid the following, which reads more like normal English?

    private boolean isAdministrator(String authCode)
    {
        return authCode.equals("01");
    }

    private boolean isFurniture(String productCode)
    {
        return productCode.equals("004") || productCode.equals("005");
    }



    Yep, if authCode is null you are in all sorts of trouble.

    Whereas "".equals(null); still works.
  • (cs) in reply to Nand

    Nand:
    It's "bad" to drag along values (retval.) The function should return as soon as it's done working.

    It's part of my company's coding standards, and I like my job, so I do it.  Someone said earlier that it's a habit.  Actually, it's a preference.  So is using multiple returns.  I doubt that one is better than the other, but if there's an industry standard, there's generally a reason for it, and it's probably better to code to that standard, if only so that your code is seen to be "professional" by such non-techie types as managers and human resources reps... particularly those who view samples of your work during interviews.

  • (cs) in reply to Bullet
    Bullet:

    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.

     

    What about

    return (condition1(x) || !condition2(x) || condition3(x));



    incorretly returns true if all conditions evaluate to false; incorrectly evaluates codition3 if condition1(x) == false and condition2(x)==true
  • Eddow (unregistered) in reply to ammoQ
    ammoQ:
    Bullet:

    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.

     

    What about

    return (condition1(x) || !condition2(x) || condition3(x));



    incorretly returns true if all conditions evaluate to false; incorrectly evaluates codition3 if condition1(x) == false and condition2(x)==true


    should then simply be
    return (condition1(x) || !condition2(x)) && condition3(x));
  • Eddow (unregistered) in reply to Eddow

    ERRATA

    okay, I get out, it doesn't work better :)

    so, i'm going to spend some minutes to find out a way =)

  • Eddow (unregistered) in reply to Eddow

    c1 || (!c2 && c3)
    that's marvelous
    I stop flooding here, thanks for listening :p

  • (cs) in reply to kipthegreat
    kipthegreat:
    Anonymous:

    davewalthall:

    PS An even stronger statement of the idiom is:
      return (cond ? a : b);

    Or, as I saw it in a few places while at Microsoft:

    return !!cond;

    Seriously.



    Sometimes the !! "operator" makes sense.  In the C++ code where I work, we use COM objects, and "smart pointers", which are actually objects with a pointer and a reference count.  The operators are overloaded so you can use them exactly like pointers.  So "!spObj" returns true if a smart pointer is "null".  So to see if it is NOT null, you use "!!spObj".  It threw me for a loop the first time I saw it, but once you get used to it it makes sense.

    But in the case of a boolean condition like you mentioned... yeah it doesn't make much sense.


    If you're using the _com_ptr_t class (or maybe CComPtr too, I've never used that), there's no need for the !!. They define an operator bool, which allows for automatic conversions to a bool for if statements and such. If it's your own class, maybe put in something like

    bool smartptr::operator bool() {return !!(*this);}


    //first post here, let's hope it doesn't get fubared...
  • LionsPhil (unregistered) in reply to kipthegreat

    kipthegreat: "Opera is for hippies, gays, and terrorists.  Use Firefox.  It's what the cool kids are using."

    In /this/ place, I can't tell if that's biting satire of a far too large section of the rabit Firefox fanboy community, or an actual Firefox fanboy.

    Either way, I suppose I'd better live up to this hippy, gay, terrorist slander and kill you with an exploding hamster of peace.

  • bob jones (unregistered)

    Good- but for full points, I'm afraid, you've got to throw in the ternary operator:

    private boolean is004or005(String prodCode)
    {
    if ("004".equals(prodCode)) return true;
    else if ("005".equals(prodCode)) return true;
    else return false;
    }

    becomes:
    private boolean is004or005(String prodCode)
    {
    return "004".equals(prodCode)? true: "005".equals(prodCode)? true: false;
    }
    Also- I'd  prefer to see "004" and "005" be made into parameters- preferably enums.

  • IDontGiveADamm (unregistered)

    What a bunch of vagina's, the code's not right, wa, wa, I am of course assuming it works, not all code in "perfect" to everyone's standards, in fact I would bet less than 20% would pass a large group of nerds review.

    So you could do it better, we all could, but it works and get over it! Now you would certainly point out how that's not the way to do it.

    It is truly a WTF though!

     

  • Pasa (unregistered) in reply to Alun Jones
    Anonymous:

    Or, as I saw it in a few places while at Microsoft:

    return !!cond;

    Seriously.

    Why, I wrote stuff like that. With reason: cond is often a function that returns BOOL, as a magnitude of stuff does in MFC. BOOL is a typedef for int, not bool, and when it is converted to the bool return type of the function the compiler will give a warning like 'performance whatever: forcing int to bool'

    You may be in a situation where turning off that warning is not preferred -- but !! eliminate it for good while the generated code is identical.

     

  • (cs) in reply to mrprogguy
    mrprogguy:

    Why would you need to protect a <font face="Courier New">return</font> with an <font face="Courier New">else</font>?  If the return is exercised, then the other clause is ignored! 



    You're right - who needs code clarity when you can save 5 bytes of precious hard disk space?

  • (cs) in reply to Thuktun
    Thuktun:

    No, that's not self-documenting enough. It must instead read:

    if ( true == condition ) return true;
    else return false;

    if ( true == condition ) return true;
    else if ( false == condition ) return false;
    else throw new OkThisIsRediculousException();

  • (cs) in reply to Tyler

    Though you have to be careful not to write

    if(a)
      if(b) f();
    else g();
     
    thinking you're being cool for not using braces.


    Or get really cocky and start putting things all on one line.

    lock(); stuff(); unlock();

    if(a) lock(); stuff(); unlock();


  • (cs) in reply to reed


    Oops, this is in reply to an old post that said:

    Tyler:

    								<table cellpadding="2" cellspacing="0" width="100%">
    									<tbody><tr>
    										<td align="left" nowrap="nowrap" valign="top"><br></td>
    									</tr>
    									<tr>
    										<td class="txt4" align="right" height="25"><br></td>
    									</tr>
    								</tbody></table>
    								
    													
    						
    									
    									
    												
    							
    								<table align="left" border="0" cellpadding="0" cellspacing="2" width="100%">
    									<tbody><tr>
    										<td rowspan="2" width="1">
    											  
    											  <img src="../Themes/default/images/spacer.gif" height="100" width="1">
    										</td>	
    										<td colspan="3" class="txt4" style="padding-top: 4px;" valign="top" width="100%">
    											<table align="left" cellpadding="0" cellspacing="0" width="90%">
    												<tbody><tr>
    													<td class="txt3" align="left" valign="top">											
    														I agree.&nbsp; I like the style:<br><span style="font-family: Courier New;">if (condition) doStuff;<br><span style="font-family: Arial;"><br><span style="font-family: Garamond;">instead of<br><span style="font-family: Courier New;">if (condition) {<br>&nbsp;&nbsp;&nbsp; doStuff<br>}<span style="font-family: Garamond;"><br><br>I think it's more readable. <br></div></BLOCKQUOTE><br><br></span></span></span></span></span></td></tr></tbody></table></td></tr></tbody></table></span><br><br><BLOCKQUOTE class="Quote"><div><i class="icon-quote"></i> <strong>reed:</strong></div><div>Though you have to be careful not to write<br><br>if(a)<br>&nbsp; if(b) f();<br>else g();<br>&nbsp;<br>thinking you're being cool for not using braces.<br><br><br>Or get really cocky and start putting things all on one line.<br><br>lock(); stuff(); unlock();<br><br>if(a) lock(); stuff(); unlock();<br><br><br></div></BLOCKQUOTE>
    
  • (cs) in reply to reed
    Funny quote that someone pointed to:
     
    "We started off at violeticulous, then as it got sillier it passed blueiculous and reached greeniculous; but it didn't stop there, and got more and more stupid, going through yellowiculous and orangeiculous and reaching the final red-hot state of ultimate absurdity."
  • (cs) in reply to themuppeteer
    Anonymous:

    Coughptcha:
    reed:
    You are number six!
    I am not a number. I am a free man!

    I was actually waiting for this answer ;)



    Yeah but nobody said  "Who.is01()?"


  • J. B. Rainsberger (unregistered)

    Well, there's some good news: at least all the comparisons have the literal on the left to avoid Null Pointer Exceptions.

    Further good news: this is easily and mechanically refactored to something potentially useful.

    I can't figure out how to spin this positively beyond that. Sorry.

  • maht (unregistered) in reply to FredSaw
    FredSaw:

    Our company best practices says a method should have only one "return" statement.  Also says braces should enclose even one line of conditional code. Based on that we would code it as:

    string retVal = b;
    if (cond)
    {
        retVal = a;
    }
    return retVal;

    In the case of just two items like this, though, it does make more sense to use:

    return (cond) ? a : b;

    But for the code in the first post above, I'd get rid of the functions and use switch case.





    if (cond)
    {
        retVal = a;
        goto exitfunction;
    }

    retVal = b;

    exitfunction:
    return retVal;


  • maht (unregistered) in reply to ChiefCrazyTalk
    Anonymous:

    Nand:

    That case should be avoided as well. It's "bad" to drag along values (retval.) The function should return as soon as it's done working.

    OK, I only actually had one formal programming class in my life, and that was in 1983, but "Back in the day" we were always tought never to have multiple exit points for any function. 



    The "one return value" is a throwback to when "structured programming" became fashionable in the 80s
  • (cs) in reply to ChiefCrazyTalk

    I agree that the single-return-point has its merits.  I still believe the drawbacks outweigh the gains.

    When you have multiple natural points, but are forced into the single return idiom, you're going to run out of room to indent:

    if (!cond_a)
    {
         ....
        if (!cond_b)
        {
            ...
            if (!cond_c)
            {
               // getting ridiculous
            }
         }
    }
    return retval;

    That

  • (cs) in reply to Stoffel

    ...drives me nuts (guess I shouldn't accidentally hit the "HTML" tab mid-post and try to flip back to "Design").

  • Pyromancer (unregistered) in reply to Maurits

    surely they meant

    private <FONT color=#0000ff>String</FONT> isBrillant(String authCode)
    {
      if ("Brillant".equals(authCode)) return <FONT color=#0000ff>"Paula"</FONT>;
    }

     

  • verisimilidude (unregistered) in reply to Master Rick
    Anonymous:


    That's not all this troll can't spell! the guy even struggled with one of the most basic spelling rules with: 'beleived'. I remember learning a rhyme about 'I before E except after C....' when I was about 6. Even my 4 year old sister whose first language is Czech, not English, can cope with that one!


    or when sounded like "A" (as in neighbor and weigh)
    or the case where a word ending in e does not drop the final vowel when forming the continuous present tense (as in seeing)
    or the few special cases that do not follow any rule (mostly stuff imported from another language)!


  • J. B. Rainsberger (unregistered) in reply to emurphy

    Yes. Your version throws NullPointerExceptions. The original does not.

  • Dave Barry (unregistered) in reply to LionsPhil
    Anonymous:
    Either way, I suppose I'd better live up to this hippy, gay, terrorist slander and kill you with an exploding hamster of peace.

    "Exploding Hamsters of Peace" would make a great name for a band.

  • (cs) in reply to maht

    Anonymous:

    if (cond)
    {
        retVal = a;
        goto exitfunction;
    }

    retVal = b;

    exitfunction:
    return retVal;

    You use goto?  Expect hellfire and brimstone to rain down on you at any moment...

  • Tyler (unregistered) in reply to Thomas Ammitzb&#248;ll-Bach
    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    bool retval;
    if (condition1(x)) {

      retval = true;
    } else if (condition2(x)) {
      retval = false;
    } else
    if (condition1(x)) {
      retval = true;
    } else {
      retval = false;
    }
    return retval;


    I assume you mean condition3 on that last one.  while that code surely does work imagine if you are wrting a performance critical program.  you just used 1 declaration and 4 assignments which are totally worthless...  and that's assuming your compiler can skips the reast of the if else ladder if it finds a condition true.

    return condition1(x) || !condition2(x) || condition3(x);
    that's a great way to do it and it will work perfectly.  that is... assuming your compiler/language uses short circuit boolean evaluation of the operator ||




  • Tyler (unregistered) in reply to Tyler

    I just realized if c1 is false and c2 is true you have an error because c3 gets excecuted and you didn't want c3 to get run at all.

  • John Hensley (unregistered) in reply to Tyler
    Anonymous:
    I assume you mean condition3 on that last one.  while that code surely does work imagine if you are wrting a performance critical program.  you just used 1 declaration and 4 assignments which are totally worthless...  and that's assuming your compiler can skips the reast of the if else ladder if it finds a condition true.

    You don't seem all that knowledgeable about compilation.

  • sonOfAMother (unregistered)

    Why not use:

    authCode.equals("01")
    instead of:
    "01".equals(authCode)

  • Tyler (unregistered) in reply to sonOfAMother

    " You don't seem all that knowledgeable about compilation."

    I most certainly am not a compiler expert.

  • (cs) in reply to sonOfAMother
    SomeSonOfAMother:
    Why not use:
    authCode.equals("01")
    instead of:
    "01".equals(authCode)


    I'm getting the distinct feeling not everyone read all the posts before replying (as I do)...

    Btw, isn't this thread flooded with more logically incorrect code than normally? WTF???
  • Foomarer (unregistered) in reply to [email protected]
    Anonymous:
    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.


    Well this would work and is neat, but it could take a tad longer to understand I suppose.. but having side-effects is going to make it difficult to understand as is..

    return condition1(x) || !condition2(x) || condition3(x);


    PS:  Does the captcha work on the first try for anyone??

    Hah, sure, returns true if condition2(x) is false instead of evaluating condition3, and it returns true if condition2(x) is true and condition3(x) is true while it should return false

    Fucking great refactoring.

    Bullet:

    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.

     

    What about

    return (condition1(x) || !condition2(x) || condition3(x));

    See above

  • Anthony (unregistered) in reply to Eddow
    Anonymous:
    ammoQ:
    Bullet:

    Anonymous:
    for those that think multiple return statements are for the devil here is some code for you to write neatly and in a manner that is easier to understand than the following:

    say you have functions condition[n](x) that modify the value of x and return a boolean.

    if (condition1(x)) return true;
    if (condition2(x)) return false;
    if (condition3(x)) return true;
    return false;

    remember that the conditionals must be performed in order because they have side effects.  And I know that I'll get a bunch of flack for have side effects of functions but sometimes that really is the best way.

     

    What about

    return (condition1(x) || !condition2(x) || condition3(x));



    incorretly returns true if all conditions evaluate to false; incorrectly evaluates codition3 if condition1(x) == false and condition2(x)==true


    should then simply be
    return (condition1(x) || !condition2(x)) && condition3(x));


    All of this rather proves the point: the original version with multiple returns is far more readable and maintainable, for the simple reason that it's how people think.
  • Anthony (unregistered) in reply to Eddow
    ammoQ:


    should then simply be
    return (condition1(x) || !condition2(x)) && condition3(x));


    If Condition1 is true, that expression will go on to evaluate Condition3, which the original did not, and if Condition3 is false ther answer will be different, so again it is incorrect.

    As I said, the original with multiple return points is far easier to read and understand, thus blowing this "law" out of the water.
  • (cs) in reply to Anthony
    Anthony:
    ammoQ:


    should then simply be
    return (condition1(x) || !condition2(x)) && condition3(x));


    If Condition1 is true, that expression will go on to evaluate Condition3, which the original did not, and if Condition3 is false ther answer will be different, so again it is incorrect.

    As I said, the original with multiple return points is far easier to read and understand, thus blowing this "law" out of the water.


    Learn to quote, Anthony. I didn't write that.
  • (cs) in reply to maht
    maht:


    if (cond)
    {
        retVal = a;
        goto exitfunction;
    }

    retVal = b;

    exitfunction:
    return retVal;



    Why not just change that to...

        if (cond)
        {
            // Do something useful...

            retVal = a;
        }
        else
        {
            // Do something else useful...

            retVal = b;
        }

        return retVal;

    ...instead?  You get the single return point you want, plus the added bonus of improved readability without having to unleash the blinding, unholy power of a goto.

    Between you and me, I think else is really just an labelless goto in disguise.  But don't tell anyone, ok?
  • floh (unregistered) in reply to Alun Jones
    Anonymous:

    Or, as I saw it in a few places while at Microsoft:

    return !!cond;

    Seriously.

     

    Hello (im fresh here, writin' the very first time ,-)

     

    The statement "return !!cond;" is used to normalize the result to false and true, whatever the input value "cond" ist. One sees this is coding from C.

    It's farly short, but in my opinion and technically all right!

     

    floh

  • Average Joe (unregistered) in reply to John Hensley
    John Hensley:
    Anonymous:
    I assume you mean condition3 on that last one.  while that code surely does work imagine if you are wrting a performance critical program.  you just used 1 declaration and 4 assignments which are totally worthless...  and that's assuming your compiler can skips the reast of the if else ladder if it finds a condition true.

    You don't seem all that knowledgeable about compilation.



    You should enlighten us all with your vast knowledge.
  • John Hensley (unregistered) in reply to Average Joe
    Anonymous:
    John Hensley:
    Anonymous:
    I assume you mean condition3 on that last one.  while that code surely does work imagine if you are wrting a performance critical program.  you just used 1 declaration and 4 assignments which are totally worthless...  and that's assuming your compiler can skips the reast of the if else ladder if it finds a condition true.

    You don't seem all that knowledgeable about compilation.

    You should enlighten us all with your vast knowledge.

    It would be easier to write some code and look at the assembly code that comes out of the compiler.

    Some people come here, I hope, to learn what not to do when programming, so I think it's appropriate to point out when someone recommends coding a particular way based on basically wrong assumptions about how compilers work -- such as the assumption that programs somehow have to "pass through" a branch that isn't taken.

  • (cs) in reply to John Hensley
    Anonymous:
    Anonymous:
    John Hensley:
    Anonymous:
    I assume you mean condition3 on that last one.  while that code surely does work imagine if you are wrting a performance critical program.  you just used 1 declaration and 4 assignments which are totally worthless...  and that's assuming your compiler can skips the reast of the if else ladder if it finds a condition true.

    You don't seem all that knowledgeable about compilation.

    You should enlighten us all with your vast knowledge.


    It would be easier to write some code and look at the assembly code that comes out of the compiler.

    Some people come here, I hope, to learn what not to do when programming, so I think it's appropriate to point out when someone recommends coding a particular way based on basically wrong assumptions about how compilers work -- such as the assumption that programs somehow have to "pass through" a branch that isn't taken.


    Quite.

    Another thing is that there are some people who know a more about certain areas.  This is more valuable than ignorance.  The poster two up should consider this instead of blabbing.  The attitude that someone who knows should be scorned for knowing leads to WTFs.  In this case, the knowledge about compilers being referred to is insultingly basic and should be known by anyone using a compiler.  No vast knowledge is needed.

    Sincerely,

    Gene Wirchenko

  • (cs) in reply to John Hensley
    Anonymous:

    It would be easier to write some code and look at the assembly code that comes out of the compiler.

    Some people come here, I hope, to learn what not to do when programming, so I think it's appropriate to point out when someone recommends coding a particular way based on basically wrong assumptions about how compilers work -- such as the assumption that programs somehow have to "pass through" a branch that isn't taken.



    Actually, some CPU architectures (e.g. ARM) allow conditional execution of most statements (not only jumps), so it's quite possible that the program passes through the branch that isn't taken, though it doesn't do anything there. That's because a jump is relative expensive, especially without branch prediction.
  • John Hensley (unregistered) in reply to Gene Wirchenko
    Gene Wirchenko:
    In this case, the knowledge about compilers being referred to is insultingly basic and should be known by anyone using a compiler.

    I wouldn't go that far. It should be known by anyone making performance suggestions.

    And yeah, ammoQ showed me up a little. But that's a case where the compiler sends the program through the alternate branch to improve performance, not because it's not smart enough to skip over.

  • (cs) in reply to Tyler

    When you put the condition and the resulting action on the same line, in most IDE's you cannot set a breakpoint on the action alone, the debugger always breaks regardless of the value of the conditon. This is not always what I want.

  • BAReFOOt (unregistered) in reply to Coughptcha

    Then look at your passport! You ARE in fact an ID to your state! ;P
    (A resource-id to be exactly. Only in use as long as of use.)

    ----
    P.S.: CAPTCHA WTF? Is "boko" a word?? Or is it "boo"?
    Can Alex please explain for us all, why he's still using that poor forum software despite the many complains he gets about it? Is it that there is a special features that makes it rock? Or is it the "Internet Explorer User" syndrome? (The one where poeple think they can't let loose from IE because it is "faster" or has this one special feature FF has not (ignoring that there is an extension for it or that it is simply irrelevant when you compare it to the consequences of using IE.))

    P.P.S.: Okay. As always, the first captcha does not work... Seriously... Quad-WTF?

    P.P.P.S: Okay. I know i wrote it correctly because it was pretty easy. But again it did not work. No comment! This time it is "china" just for the log...

  • Stephan Dhaene (unregistered) in reply to MikeMontana

    Well guys, believe it or not: I've worked on this project and it's for real! Better still: this stuff is used to calculate our PENSIONS and other social security!!! So I better start putting my money in a sock or matres :-(

    Cheers,

  • anonymous expert (unregistered) in reply to Stephan Dhaene

    If you don't allow more than one return statement and obviosly no gotos, then why allow stuff like break or continue?

    Consider the following:
    for (unsigned i = 0; i< L ; ++i) {
       if (someCondition(array[i])) break;
       doStuff;
    }
    to stop when the conidition is met.
    now try it with nested loops:

    for (unsigned i = 0; i< L ; ++i) {
      for (unsigned j = 0; j< L ; ++j) {
       if (someCondition(array[i][j])) break;
       doStuff;
      }
    }
    The break only stops the inner loop. A goto to the end might be smart here if you want to continue or a return in case it's the only thing to do:
    bool func () {
      for (unsigned i = 0; i< L ; ++i) {
         if (someCondition(array[i])) return true;
         doStuff;
      }
      // condition wasn't met
      return false;
    }

    Now if you want to use that "retval", you'd have to make something like:

    bool func () {
      bool retVal = false;
      for (unsigned i = 0; i< L ; ++i) {

         if (someCondition(array[i])) {
             retVal = true;
             .... break? goto?
         }
         doStuff;
      }
      return retVal;

    }
    or use something like:

    bool func () {
      bool retVal = false;

      for (unsigned i = 0, bool end_loop = false ; i< L || loop_end ; ++i) {

         if (someCondition(array[i])) {
             retVal = true;
             end_loop = true;
             ... continue? // surely it's better than trying to skip doStuff with a conditional.
         }
         doStuff;

      }
      return retVal;

    }

    -----------------------------------------
    Another example... many times you want to do something only if certain pre-conditions are met, or optimizing by "short-circuiting", for example:
    bool func() {
      if (!condition1) return false;
      doComputationRequiringCondition1;
      if (!condition2) return false;
      doComputationRequiringCondition2;
      // all conditions met, true!
      return true;
    }

    And for those who might have thought otherwise, at least in C, C++, java, C#, perl the following happens for this line of code:
    if (f() && g()) { doSomething; }
    f() is first called,
    if it evaluates to false, it continues to the next line, without evaluating g().
    if it evaluates to true, g() is called
    if it evaluates to true, "doSomething" will occur
    if it evaluates to false, it continues to the next line.

    so assume cond2 requires cond1 for its calculation (for example, cond1 checks if x is positive and cond2 takes the square root of cond1....) then writing:
    if (cond1(x) && cond2(x))...... is completely logical and cond2 will NOT run if cond1 fails.

Leave a comment on “Refactoring to the Max”

Log In or post as a guest

Replying to comment #:

« Return to Article