Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. A Programming Question

A Programming Question

Scheduled Pinned Locked Moved The Lounge
questioncom
40 Posts 29 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Nish Nishant

    Marc Clifton wrote:

    void Foo()

    Marc Clifton wrote:

    return ret;

    *ahem* Nish :-D

    M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #11

    Nishant Sivakumar wrote:

    *ahem*

    You realize you're the first one to catch that. :-D Good call! I may harrass people about spelling errors, but those are nothing compared to a bad programming example error! Marc VS2005 Tips & Tricks -- contributions welcome!

    S R 2 Replies Last reply
    0
    • M Marc Clifton

      Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

      J Offline
      J Offline
      Jeremy Falcon
      wrote on last edited by
      #12

      I use a return variable that gets assigned a default value. This way I can make sure that I'm always returning a valid value. I do break loops when the time calls for it, mainly because I don't want my code to be inefficient. Although I tend to use to use the break statement sparingly, more so I will use continue. If I need to break the iteration completely I'll do so in the conditions if possible (unless I’m modifying someone else’s code – I don't make many changes as possible in that regard because you never know what impact it could have on the system). The main reason I do this is because for a long method it makes it easier to follow the flow of execution IMO. Jeremy Falcon

      1 Reply Last reply
      0
      • G Graham Bradshaw

        Drew Stainton wrote:

        never use break in loops

        What, never? Doesn't that make any linear search you do (for example finding a particular element in an array) a bit inefficient? Once you've found what you're looking for, surely you don't process the rest of the elements anyway?

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #13

        Graham Bradshaw wrote:

        surely you don't process the rest of the elements anyway?

        Of course not! That's what I meant by 'I include the variable in the conditional for the loop' For a linear search, the variable would be set to 'found' and the loop would terminate in the conditional on the next iteration. Cheers, Drew.

        1 Reply Last reply
        0
        • N Nish Nishant

          Marc Clifton wrote:

          void Foo()

          Marc Clifton wrote:

          return ret;

          *ahem* Nish :-D

          J Offline
          J Offline
          Jeremy Falcon
          wrote on last edited by
          #14

          :laugh: I passed right over that one. Jeremy Falcon

          1 Reply Last reply
          0
          • M Marc Clifton

            Drew Stainton wrote:

            I start by assigning a default return value to a local variable and then use that variable as part of the conditional in whatever loops I'm using - nested or otherwise.

            Ah, very nifty! 20 years of programming, and I never thought of that. In fact, I don't think I've even ever seen it in other people's code. :doh: Marc VS2005 Tips & Tricks -- contributions welcome!

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #15

            I rarely ever see this done as well. It's not as efficient as using 'break' because the loop has to hit the conditional for the next iteration before it can end. I find it much easier to read and debug. I was big on state and flow diagrams many years ago and this made it much easier to relate the diagrams to the implementation. Cheers, Drew.

            1 Reply Last reply
            0
            • M Marc Clifton

              Drew Stainton wrote:

              I start by assigning a default return value to a local variable and then use that variable as part of the conditional in whatever loops I'm using - nested or otherwise.

              Ah, very nifty! 20 years of programming, and I never thought of that. In fact, I don't think I've even ever seen it in other people's code. :doh: Marc VS2005 Tips & Tricks -- contributions welcome!

              B Offline
              B Offline
              Blake Miller
              wrote on last edited by
              #16

              Really :omg: Not even: Something* SearchForSomething(...) { Something* pSomethingTested; Something* pSomethingFound = NULL; while( !pSomethingFound ){ pSomethingTested = GetPointertoWhatever(); if( pSomethingTest matches my search criteria ){ pSomethingFound = pSomethingTested; } } return pSomethingFound; } It really IS that simple and straightforward :->

              B 1 Reply Last reply
              0
              • L Lost User

                I always have one exit point at the end of the method and never use break in loops. It's akin to goto in my mind - another tool of the devil. I start by assigning a default return value to a local variable and then use that variable as part of the conditional in whatever loops I'm using - nested or otherwise. Cheers, Drew.

                L Offline
                L Offline
                Leslie Sanford
                wrote on last edited by
                #17

                Drew Stainton wrote:

                I start by assigning a default return value to a local variable and then use that variable as part of the conditional in whatever loops I'm using - nested or otherwise.

                I use this approach as well, except when you using foreach because, of course, there's no place to test the conditional as there is in a for or while loop. Of course, one could use an enumerator in a while loop instead:

                bool found = false;
                IEnumerator en = someCollection.GetEnumerator();

                while(!found && en.MoveNext())
                {
                if(en.Current == soughtAfterValue)
                {
                // Take some action.
                found = true;
                }
                }

                return found;

                However, I usually take this approach:

                bool found = false;

                foreach(SomeObject obj in someCollection)
                {
                if(obj == soughtAfterValue)
                {
                // Take some action.
                found = true;
                break;
                }
                }

                return found;

                I think either way is fine, but I think the second approach is a little clearer. So I don't think breaks within loops are automatically bad. I do like to avoid more than one return within a method, however. I break this rule from time to time if I think it will make the algorithm clearer, but I like having one return at the bottom of the method.

                L 1 Reply Last reply
                0
                • M Marc Clifton

                  Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                  J Offline
                  J Offline
                  Jamie Nordmeyer
                  wrote on last edited by
                  #18

                  Nope. I'll exit when I damn well please. ;) Kyosa Jamie Nordmeyer - Taekwondo Yi (2nd) Dan Portland, Oregon, USA

                  1 Reply Last reply
                  0
                  • M Marc Clifton

                    Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #19

                    I do try and aim on having a single exit point for methods, but with C++ it isn't quite as important IMHO (thanks to destructors and smart pointers, etc.) - and it can lead to some very deep nesting, which might not necessarily be that readable. Most people I've spoken to in the office agree that it is preferable to have a single exit point, especially when maintaining other peoples code. As for loops - I use break often. Shrug.


                    The Rob Blog
                    Google Talk: robert.caldecott

                    1 Reply Last reply
                    0
                    • M Marc Clifton

                      Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                      C Offline
                      C Offline
                      Colin Angus Mackay
                      wrote on last edited by
                      #20

                      It depends. Sometimes having just one exit point makes it easier to read. Sometimes it doesn't. I just try and write code that is easy to read and maintain. So, I don't have a hard and fast rule.


                      My: Blog | Photos "Man who stand on hill with mouth open will wait long time for roast duck to drop in." -- Confucious

                      1 Reply Last reply
                      0
                      • M Marc Clifton

                        Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                        A Offline
                        A Offline
                        Andy Brummer
                        wrote on last edited by
                        #21

                        I tend to try to keep local variables to a minimum so that multiple exit points don't cause a problem. I find they make code cleaner and easier to read as long as you don't have to change a lot of state in order to exit. Having to do that just tells me that the method is trying to do too much and needs to be simplified. I rarely have methods with blocks nested more then 1 or 2 deep, and never have nested try catch blocks.

                        1 Reply Last reply
                        0
                        • L Leslie Sanford

                          Drew Stainton wrote:

                          I start by assigning a default return value to a local variable and then use that variable as part of the conditional in whatever loops I'm using - nested or otherwise.

                          I use this approach as well, except when you using foreach because, of course, there's no place to test the conditional as there is in a for or while loop. Of course, one could use an enumerator in a while loop instead:

                          bool found = false;
                          IEnumerator en = someCollection.GetEnumerator();

                          while(!found && en.MoveNext())
                          {
                          if(en.Current == soughtAfterValue)
                          {
                          // Take some action.
                          found = true;
                          }
                          }

                          return found;

                          However, I usually take this approach:

                          bool found = false;

                          foreach(SomeObject obj in someCollection)
                          {
                          if(obj == soughtAfterValue)
                          {
                          // Take some action.
                          found = true;
                          break;
                          }
                          }

                          return found;

                          I think either way is fine, but I think the second approach is a little clearer. So I don't think breaks within loops are automatically bad. I do like to avoid more than one return within a method, however. I break this rule from time to time if I think it will make the algorithm clearer, but I like having one return at the bottom of the method.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #22

                          Leslie Sanford wrote:

                          So I don't think breaks within loops are automatically bad

                          I totally agree - didn't mean to imply they were bad. I don't like using them but that's just my choice. You're right about foreach. To be honest I don't use it if the loop has early termination conditions. In those cases I use an enumerator. I really like knowing up front all of the conditions the loop is dependent on. Cheers, Drew.

                          L 1 Reply Last reply
                          0
                          • M Marc Clifton

                            Nishant Sivakumar wrote:

                            *ahem*

                            You realize you're the first one to catch that. :-D Good call! I may harrass people about spelling errors, but those are nothing compared to a bad programming example error! Marc VS2005 Tips & Tricks -- contributions welcome!

                            S Offline
                            S Offline
                            Steve Mayfield
                            wrote on last edited by
                            #23

                            he omitted this line: #define void MyRet; :rolleyes: ;) Steve

                            J 1 Reply Last reply
                            0
                            • S Steve Mayfield

                              he omitted this line: #define void MyRet; :rolleyes: ;) Steve

                              J Offline
                              J Offline
                              Jim Crafton
                              wrote on last edited by
                              #24

                              You're Satan, aren't you? :) ¡El diablo está en mis pantalones! ¡Mire, mire! Real Mentats use only 100% pure, unfooled around with Sapho Juice(tm)! SELECT * FROM User WHERE Clue > 0 0 rows returned Save an Orange - Use the VCF!

                              1 Reply Last reply
                              0
                              • L Lost User

                                Leslie Sanford wrote:

                                So I don't think breaks within loops are automatically bad

                                I totally agree - didn't mean to imply they were bad. I don't like using them but that's just my choice. You're right about foreach. To be honest I don't use it if the loop has early termination conditions. In those cases I use an enumerator. I really like knowing up front all of the conditions the loop is dependent on. Cheers, Drew.

                                L Offline
                                L Offline
                                Leslie Sanford
                                wrote on last edited by
                                #25

                                About breaking out of foreach...

                                Drew Stainton wrote:

                                To be honest I don't use it if the loop has early termination conditions. In those cases I use an enumerator. I really like knowing up front all of the conditions the loop is dependent on.

                                You know, this is a good point. I will consider it next time I'm thinking about using foreach in that way.

                                1 Reply Last reply
                                0
                                • M Marc Clifton

                                  Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                                  M Offline
                                  M Offline
                                  malharone
                                  wrote on last edited by
                                  #26

                                  Was this a trick question?? How can you have return ret; in a function of type void??? :wtf: :wtf: But just in case if this was a typo ... Return immidiately ... - if in a simple "If" and single "Else" block. If (condition) return x; else return false; - or if in a simple switch statement If I'm implementing a complex logic in my method, then I have a single point of exit. But then again, there is no one right way. My decision making also depends on my mood :) . - Malhar

                                  1 Reply Last reply
                                  0
                                  • M Marc Clifton

                                    Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                                    L Offline
                                    L Offline
                                    leppie
                                    wrote on last edited by
                                    #27

                                    Personally I use goto's for difficult flow control, screw style! Just get it working the best it can be! [update] counted 6 goto's in the C# part of xacc :). Here's a nice example:

                                    //some code before
                                    foreach (MRUFile mru in recentfiles)
                                    {
                                    if (mru.filename == filename)
                                    {
                                    mru.Update();
                                    goto DONE;
                                    }
                                    }
                                    recentfiles.Add( new MRUFile(filename));

                                    DONE:
                                    //some code after

                                    Now I can already hear the cursing, but any other form of flow control, you need 1 or more variables to carry some (unneeded, and extra) state, and make the whole thing much less readable. :-D [update] xacc.ide-0.1-rc4 released! Download and screenshots -- modified at 16:19 Monday 14th November, 2005

                                    C 1 Reply Last reply
                                    0
                                    • M Marc Clifton

                                      Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                                      G Offline
                                      G Offline
                                      Giles
                                      wrote on last edited by
                                      #28

                                      I prescrive to that for small functions. For larger ones with multiple nested loops, I would probably just got for return statment, and highlight it with decent comments and spacing. That, or go for the dreaded goto :-D


                                      "Je pense, donc je mange." - Rene Descartes 1689 - Just before his mother put his tea on the table. Shameless Plug - Distributed Database Transactions in .NET using COM+

                                      1 Reply Last reply
                                      0
                                      • M Marc Clifton

                                        Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                                        C Offline
                                        C Offline
                                        Chris Maunder
                                        wrote on last edited by
                                        #29

                                        I have a bail-out return statement at the beginning of a function if there are immediate problems (bad input, object not setup etc), and I'll often do the same with loops (use a continue if it's immediately apparant that the loop should skip this particular iteration. And sometimes I throw in a random return path in the middle of a function because I'm evil. cheers, Chris Maunder

                                        CodeProject.com : C++ MVP

                                        1 Reply Last reply
                                        0
                                        • M Marc Clifton

                                          Really, this is a programming question. There's a philosophy about always having one exit point in a method, so, you'll typically see something like this: void Foo() { MyRet ret=null; if (blah) { ret=bar; } return ret; } Or, if it's a for loop, ret will be assigned followed by a break. First off, do you prescribe to that philosophy? Do you do so religiously? If so, what do you do when you have several nested loops, and you need to break out of the innermost one and return the value? :) Marc VS2005 Tips & Tricks -- contributions welcome!

                                          S Offline
                                          S Offline
                                          Shog9 0
                                          wrote on last edited by
                                          #30

                                          ...sorta. Non-trivial methods generally start by checking the validity of any parameters, the state of the class, etc. If any of these "sanity checks" fail, i immediately return an error. After that, i try and keep all returns at the end of the method, regardless of where the value originates. I have no qualms about using break or continue in loops though - if a loop gets to where such things would make the code hard to follow, chances are it's a good time to refactor it anyway.

                                          You must be careful in the forest Broken glass and rusty nails If you're to bring back something for us I have bullets for sale...

                                          J 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups