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. Other Discussions
  3. The Weird and The Wonderful
  4. Which code you suggest?

Which code you suggest?

Scheduled Pinned Locked Moved The Weird and The Wonderful
comquestion
103 Posts 44 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.
  • Z ZurdoDev

    I prefer the second method. I try not to have multiple places where a function can return.

    There are only 10 types of people in the world, those who understand binary and those who don't.

    A Offline
    A Offline
    Ancandune
    wrote on last edited by
    #41

    I do not see the value in always only having one return from a function. When reading the code, you still need to look through the function for every place retValue is set, so it is not easier to follow or understand. If there is some clean-up to be done, then it does make sense. But if not, why keep to this rule if it provides no benefit? In the validation example someone else posted in this thread, the early returns provide easier to read code, rather than a long block of if/then/else.

    Z 1 Reply Last reply
    0
    • A Ancandune

      I do not see the value in always only having one return from a function. When reading the code, you still need to look through the function for every place retValue is set, so it is not easier to follow or understand. If there is some clean-up to be done, then it does make sense. But if not, why keep to this rule if it provides no benefit? In the validation example someone else posted in this thread, the early returns provide easier to read code, rather than a long block of if/then/else.

      Z Offline
      Z Offline
      ZurdoDev
      wrote on last edited by
      #42

      Quote:

      the early returns provide easier to read code

      Easier to read is a matter of opinion. Some people think C# is easier to read than VB. :)

      There are only 10 types of people in the world, those who understand binary and those who don't.

      1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        What if you have two nested loops? It's a lot harder to exit them both...

        The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

        F Offline
        F Offline
        Fabio Franco
        wrote on last edited by
        #43

        throw an exception :laugh:

        To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

        1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          I think that's an unnecessary restriction - I prefer to do all my validation code / user notification en mass at the top of a method, and exit immediately.

          if (!userGotHisNameRight)
          Report It
          return
          if (!userManganagedHisAddressOK)
          Report It
          return
          if (...)
          ...
          Actual work the method is supposed to do

          The alternataive being:

          if (!userGotHisNameRight)
          Report It
          else if (!userManganagedHisAddressOK)
          Report It
          else if (...)
          ...
          else
          {
          Actual work the method is supposed to do
          }

          The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

          C Offline
          C Offline
          Cesar de Souza
          wrote on last edited by
          #44

          Exactly. I share the same view - do validation and exit as soon as possible, to avoid crippling the logic down the road.

          Interested in Machine Learning in .NET? Check the Accord.NET Framework. See also Sequence Classifiers in C# with Hidden Conditional Random Fields.

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            I think that's an unnecessary restriction - I prefer to do all my validation code / user notification en mass at the top of a method, and exit immediately.

            if (!userGotHisNameRight)
            Report It
            return
            if (!userManganagedHisAddressOK)
            Report It
            return
            if (...)
            ...
            Actual work the method is supposed to do

            The alternataive being:

            if (!userGotHisNameRight)
            Report It
            else if (!userManganagedHisAddressOK)
            Report It
            else if (...)
            ...
            else
            {
            Actual work the method is supposed to do
            }

            The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

            C Offline
            C Offline
            Cesar de Souza
            wrote on last edited by
            #45

            OriginalGriff wrote:

            I think that's an unnecessary restriction - I prefer to do all my validation code / user notification en mass at the top of a method, and exit immediately.

            Exactly. I share the same view - do validation and exit as soon as possible, to avoid crippling the logic down the road.

            Interested in Machine Learning in .NET? Check the Accord.NET Framework. See also Sequence Classifiers in C# with Hidden Conditional Random Fields.

            A 1 Reply Last reply
            0
            • R Rajesh Anuhya

              Code1:

                 Boolean DoSomething(string\[\] values)
                  {
                      foreach (string s in values)
                          if (s == "ABC")
                              return true;
                      return false;
                  }
              

              Code2:

              Boolean DoSomething(string[] values)
              {
              bool retValue = false;
              foreach (string s in values)
              if (s == "ABC")
              retValue=true;
              return retValue;
              }

              in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

              my Tip/Tricks[^] |Contact me[^]

              N Offline
              N Offline
              nocturns2
              wrote on last edited by
              #46

              If I were trying to determine if "ABC" exists in values then Code1. If I were trying to determine if the last element in values (s) was equal to "ABC" then Code2. I subscribe to early returns. Unless there is a reason to tenderize the value(s) before returning it.

              1 Reply Last reply
              0
              • Z ZurdoDev

                Quote:

                15 for anything else.

                Serious? I have lots of stored procedures that take 20 or more parameters so just adding the parameters is more code than 15 lines.

                There are only 10 types of people in the world, those who understand binary and those who don't.

                S Offline
                S Offline
                Sentenryu
                wrote on last edited by
                #47

                i don't think they count the parameter list, i've read that on a doc that came on a CP newsletter long ago, but i personally don't like that much parameters

                I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p) "Given the chance I'd rather work smart than work hard." - PHS241 "'Sophisticated platform' typically means 'I have no idea how it works.'"

                1 Reply Last reply
                0
                • C Cesar de Souza

                  OriginalGriff wrote:

                  I think that's an unnecessary restriction - I prefer to do all my validation code / user notification en mass at the top of a method, and exit immediately.

                  Exactly. I share the same view - do validation and exit as soon as possible, to avoid crippling the logic down the road.

                  Interested in Machine Learning in .NET? Check the Accord.NET Framework. See also Sequence Classifiers in C# with Hidden Conditional Random Fields.

                  A Offline
                  A Offline
                  Argonia
                  wrote on last edited by
                  #48

                  I totally agree with you guys. But its also important what your boss thins. For example when i used the same technique validations with fast returns i got scold how this shouldn't be done this way because when someone reads the code he wont understand a thing ?! And also this isn't a good practice ?!

                  Microsoft ... the only place where VARIANT_TRUE != true

                  C 1 Reply Last reply
                  0
                  • A Argonia

                    I totally agree with you guys. But its also important what your boss thins. For example when i used the same technique validations with fast returns i got scold how this shouldn't be done this way because when someone reads the code he wont understand a thing ?! And also this isn't a good practice ?!

                    Microsoft ... the only place where VARIANT_TRUE != true

                    C Offline
                    C Offline
                    Cesar de Souza
                    wrote on last edited by
                    #49

                    It seems a lot of people follow to this "rule" without ever questioning why. My manager was also an advocate of the "single return improves readability" fallacy until I explained to him why this wouldn't be the case with examples. Plus when I completely rewrote a ugly mass of haired code in our system into actually maintainable code, he was convinced. I think it needs some luck, and having open-minded management helps too.

                    Interested in Machine Learning in .NET? Check the Accord.NET Framework. See also Sequence Classifiers in C# with Hidden Conditional Random Fields.

                    1 Reply Last reply
                    0
                    • S Stefan_Lang

                      ... until you introduce code that needs clean-up at one point or another. Many of the functions I look at every day are a decade old or more, and consist of several hundred lines of codes with half a dozen levels of nesting or more. Every single one of them allocates stuff, or does something else requiring cleanup. More often than not, this happens before something else happens that necessitates a premature return. Some of the really old functions use goto exit; to immediately jump to the cleanup code. I use a flag. Sure, not everyone works on such a codebase. But the truth is, the majority of programmers doesn't work on brand-new projects either. 80% work on internal programs designed to improve certain processes inside of a single company. Lots of code, and sometimes with a lifetime higher than that of some of their current programmers. In that context, IME, premature returns are almost always a bad idea.

                      S Offline
                      S Offline
                      svella
                      wrote on last edited by
                      #50

                      Stefan_Lang wrote:

                      Some of the really old functions use goto exit; to immediately jump to the cleanup code. I use a flag.

                      That's what try..finally is for. Both goto and flags fail miserably in the presence of exceptions.

                      L S 2 Replies Last reply
                      0
                      • R Rajesh Anuhya

                        Code1:

                           Boolean DoSomething(string\[\] values)
                            {
                                foreach (string s in values)
                                    if (s == "ABC")
                                        return true;
                                return false;
                            }
                        

                        Code2:

                        Boolean DoSomething(string[] values)
                        {
                        bool retValue = false;
                        foreach (string s in values)
                        if (s == "ABC")
                        retValue=true;
                        return retValue;
                        }

                        in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

                        my Tip/Tricks[^] |Contact me[^]

                        R Offline
                        R Offline
                        RafagaX
                        wrote on last edited by
                        #51

                        Both and neither, i usually use what makes more sense in the task at hand, if the method is trivial or requires final cleanup, I prefer a single return point, if depending of a condition the code will run a lengthy or expensive task then I prefer early return.

                        CEO at: - Rafaga Systems - Para Facturas - Modern Components for the moment...

                        1 Reply Last reply
                        0
                        • R Rajesh Anuhya

                          Code1:

                             Boolean DoSomething(string\[\] values)
                              {
                                  foreach (string s in values)
                                      if (s == "ABC")
                                          return true;
                                  return false;
                              }
                          

                          Code2:

                          Boolean DoSomething(string[] values)
                          {
                          bool retValue = false;
                          foreach (string s in values)
                          if (s == "ABC")
                          retValue=true;
                          return retValue;
                          }

                          in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

                          my Tip/Tricks[^] |Contact me[^]

                          M Offline
                          M Offline
                          MarkTJohnson
                          wrote on last edited by
                          #52

                          One way in, one way out and we stop when we find the value we want.

                          Boolean DoSomething(string[] values)
                          {
                          bool bResult = false;
                          int i = 0;
                          while ( (!bResult) && (i < values.GetLength()) )
                          {
                          bResult = (values[i++] == "ABC");
                          }
                          return bResult;
                          }

                          OR

                          Boolean DoSomething(string[] values)
                          {
                          bool bResult = false;
                          int i = values.GetLength();
                          while ( !bResult && i )
                          {
                          bResult = (values[--i] == "ABC");
                          }
                          return bResult;
                          }

                          Just realized with the my second one, if the array is empty it still works. The first one does too but I like the second better and will try using that logic from now on. Thanks for making me think.

                          M__k T J.hnnnnn What my signature looks like in courier.

                          J 2 Replies Last reply
                          0
                          • R Rajesh Anuhya

                            Code1:

                               Boolean DoSomething(string\[\] values)
                                {
                                    foreach (string s in values)
                                        if (s == "ABC")
                                            return true;
                                    return false;
                                }
                            

                            Code2:

                            Boolean DoSomething(string[] values)
                            {
                            bool retValue = false;
                            foreach (string s in values)
                            if (s == "ABC")
                            retValue=true;
                            return retValue;
                            }

                            in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

                            my Tip/Tricks[^] |Contact me[^]

                            J Offline
                            J Offline
                            James Lonero
                            wrote on last edited by
                            #53

                            I prefer #3 offered by "NeverJustHere": return values.Contains("ABC"); Each will get the same result, except #2 wastes unnecessary cycles. #3 is best because it is the most efficient, uses the least about of your code, and is already debugged (hopefully MS did their job). The example in #2 can be made more efficient if you change it to: Boolean DoSomething(string[] values) { bool retValue = false; foreach (string s in values) if (s == "ABC") { retValue=true; break; } return retValue; }

                            1 Reply Last reply
                            0
                            • R Reelix

                              You left out the ;

                              -= Reelix =-

                              K Offline
                              K Offline
                              KP Lee
                              wrote on last edited by
                              #54

                              Reelix wrote:

                              You left out the ;

                              :laugh: Well, the benefit of your first option is that it is faster as has already been mentioned. Sometimes built-in's are faster. For that reason you might want to look at the built-in function. I read that someone thought the bubble sort put in an article was very efficient. I'm going "Oh G.., save us from inexperienced programmers" Built the bubble sort, a slightly more efficient version, and my binary sort routine I (re)wrote after seeing that #%#$@. I stopped testing performance of the bubble sort at 200K (over 2 minutes) I threw in the built in sort routine too. Both were sorting 200K in sub-second times. After getting up there in size, the built-in was performing in about 2/3 the time my routine was. In Big O, the bubble was N^2 and time tests matched that estimated. I stopped testing mine at 150M (space ran out at 200M) Built-in 29 seconds, mine 49 seconds, slightly faster than 2/3. I estimated the bubble would finish in 750 squared times 130 seconds.

                              1 Reply Last reply
                              0
                              • R Rajesh Anuhya

                                Code1:

                                   Boolean DoSomething(string\[\] values)
                                    {
                                        foreach (string s in values)
                                            if (s == "ABC")
                                                return true;
                                        return false;
                                    }
                                

                                Code2:

                                Boolean DoSomething(string[] values)
                                {
                                bool retValue = false;
                                foreach (string s in values)
                                if (s == "ABC")
                                retValue=true;
                                return retValue;
                                }

                                in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

                                my Tip/Tricks[^] |Contact me[^]

                                J Offline
                                J Offline
                                jibalt
                                wrote on last edited by
                                #55

                                It's tragic that anyone would ask this, since the second chunk of code is so clearly inferior. But I would of course write

                                return values.Any(s => s == "ABC")

                                1 Reply Last reply
                                0
                                • R Rajesh Anuhya

                                  Code1:

                                     Boolean DoSomething(string\[\] values)
                                      {
                                          foreach (string s in values)
                                              if (s == "ABC")
                                                  return true;
                                          return false;
                                      }
                                  

                                  Code2:

                                  Boolean DoSomething(string[] values)
                                  {
                                  bool retValue = false;
                                  foreach (string s in values)
                                  if (s == "ABC")
                                  retValue=true;
                                  return retValue;
                                  }

                                  in the above 2 codes which code you will suggest and why? waiting for your valuable comments. Thanks --RA

                                  my Tip/Tricks[^] |Contact me[^]

                                  J Offline
                                  J Offline
                                  jibalt
                                  wrote on last edited by
                                  #56

                                  You have posted in the wrong place. The guidelines say no programming questions . This forum is purely for amusement and discussions on code snippets. All actual programming questions will be removed.

                                  1 Reply Last reply
                                  0
                                  • M MarkTJohnson

                                    One way in, one way out and we stop when we find the value we want.

                                    Boolean DoSomething(string[] values)
                                    {
                                    bool bResult = false;
                                    int i = 0;
                                    while ( (!bResult) && (i < values.GetLength()) )
                                    {
                                    bResult = (values[i++] == "ABC");
                                    }
                                    return bResult;
                                    }

                                    OR

                                    Boolean DoSomething(string[] values)
                                    {
                                    bool bResult = false;
                                    int i = values.GetLength();
                                    while ( !bResult && i )
                                    {
                                    bResult = (values[--i] == "ABC");
                                    }
                                    return bResult;
                                    }

                                    Just realized with the my second one, if the array is empty it still works. The first one does too but I like the second better and will try using that logic from now on. Thanks for making me think.

                                    M__k T J.hnnnnn What my signature looks like in courier.

                                    J Offline
                                    J Offline
                                    jibalt
                                    wrote on last edited by
                                    #57

                                    I refuse to hire anyone who subscribes to that inane single exit nonsense.

                                    M 1 Reply Last reply
                                    0
                                    • M MarkTJohnson

                                      One way in, one way out and we stop when we find the value we want.

                                      Boolean DoSomething(string[] values)
                                      {
                                      bool bResult = false;
                                      int i = 0;
                                      while ( (!bResult) && (i < values.GetLength()) )
                                      {
                                      bResult = (values[i++] == "ABC");
                                      }
                                      return bResult;
                                      }

                                      OR

                                      Boolean DoSomething(string[] values)
                                      {
                                      bool bResult = false;
                                      int i = values.GetLength();
                                      while ( !bResult && i )
                                      {
                                      bResult = (values[--i] == "ABC");
                                      }
                                      return bResult;
                                      }

                                      Just realized with the my second one, if the array is empty it still works. The first one does too but I like the second better and will try using that logic from now on. Thanks for making me think.

                                      M__k T J.hnnnnn What my signature looks like in courier.

                                      J Offline
                                      J Offline
                                      jibalt
                                      wrote on last edited by
                                      #58

                                      I refuse to hire anyone who subscribes to that inane single exit nonsense. And that code is awful for other reasons too. The correct code is

                                      return values.Any(s => s == "ABC")

                                      unless it can be proved to be a performance bottleneck.

                                      P 1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        Yes you can, but...a return is a lot, lot cleaner!

                                        The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)

                                        R Offline
                                        R Offline
                                        Renzo Ciafardone
                                        wrote on last edited by
                                        #59

                                        No, is not. This "one return only" style you talk about always produces uglier code, and is usually slower. This is clearly a personal style preference of yours and you are entitled to it, but if you think there is a general rule that recommends only one return then you should know you are wrong.

                                        1 Reply Last reply
                                        0
                                        • S Stefan_Lang

                                          Neither. IMHO the best approach for a non-trivial function is to use a single return value declared and initialized at the start, along with a flag indicating premature abortion. Then, over the whole length of your function, no matter how long it is, you can always add that flag to every loop or (top level) if statement to prevent unnecessary execution of code. In the example above, the return value can double as abortion flag: use it to prematurely break out of the loop to prevent unnecessary execution of code. Personally, for any function with more than about half a dozen of control statements, I introduce a boolean variable called 'done' or similar that I use to short-cut later control statements. This way I don't normally need to increase the nesting level by more than 1.

                                          R Offline
                                          R Offline
                                          Renzo Ciafardone
                                          wrote on last edited by
                                          #60

                                          The idea of adding an additional unnecessary variable for "control" is anathema to me. Think of it, you are wasting an assignation and then you are adding an extra comparison for each block that fails plus the one that's actually true. Put that into a function that repeat a few thousand times and you got yourself a waste of time well into the millisecond range if not more, and lot of extra work for the GC. I am not against flags, God knows i used them a lot, they are a valid control, but not in this case where you are using it as a sort of eufenism for a return

                                          S 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