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.
  • 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[^]

    S Offline
    S Offline
    Simon ORiordan from UK
    wrote on last edited by
    #21

    Code 1 would be my preference as it is the default indentation model for Visual Studio. I don't see the point of re-setting the default model or turning off the auto-complete for the sake of a preference; I find that the usual combination of indents provides a readable and fast coding format which is pretty good at revealing errors and incomplete blocks due to items not aligning conventionally. In other words, you can pick up errors in peripheral vision, which is quick.

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

      A Offline
      A Offline
      Andrew Leeder
      wrote on last edited by
      #22

      No. Actually it isn't. All you have to do (hush my mouth) is add a label to your single return point at the bottom of your procedure, and then (and I can't believe I'm saying this in open forum) "goto" that label. Simples! Yes - I am more than old enough to know better but I do still use goto from time to time and I'm not totally averse to the odd setjmp/longjmp pair in my code. ;P

      OriginalGriffO 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[^]

        V Offline
        V Offline
        vonb
        wrote on last edited by
        #23

        I would go with #1. Number 2 should have a break statement and would work too.

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

        The signature is in building process.. Please wait...

        1 Reply Last reply
        0
        • A Andrew Leeder

          No. Actually it isn't. All you have to do (hush my mouth) is add a label to your single return point at the bottom of your procedure, and then (and I can't believe I'm saying this in open forum) "goto" that label. Simples! Yes - I am more than old enough to know better but I do still use goto from time to time and I'm not totally averse to the odd setjmp/longjmp pair in my code. ;P

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #24

          Or use a return, which is cleaner, and a lot more obvious...and won't get you strung up by the "goto is evil" lynch mob. And in this case it would be a horrible and unnecessary use of goto which would probably be deserving of the hempen necktie!

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

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          S 1 Reply Last reply
          0
          • Z ZurdoDev

            Quote:

            it can be difficult to follow retValue around the function to find out where you are really setting the return value.

            That's funny. That's the same reason people usually argue for single exit, in that it is hard to figure out why some code isn't running because it turns out there was a return statement earlier that you hadn't noticed. :) To each his own.

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

            N Offline
            N Offline
            Nicholas Marty
            wrote on last edited by
            #25

            I also go mostly for early exit. This helps to keep the code to the left as much as possible. Besides. if a method gets too long... you're doing it wrong ;)

            S 1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              Or use a return, which is cleaner, and a lot more obvious...and won't get you strung up by the "goto is evil" lynch mob. And in this case it would be a horrible and unnecessary use of goto which would probably be deserving of the hempen necktie!

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

              S Offline
              S Offline
              SortaCore
              wrote on last edited by
              #26

              Interestingly, the only use MS recommends for goto is exiting multiple loops.

              OriginalGriffO 1 Reply Last reply
              0
              • S SortaCore

                Interestingly, the only use MS recommends for goto is exiting multiple loops.

                OriginalGriffO Offline
                OriginalGriffO Offline
                OriginalGriff
                wrote on last edited by
                #27

                Yes, but MS recommends you install Windows 8 on your computer...

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

                "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                S 1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  Yes, but MS recommends you install Windows 8 on your computer...

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

                  S Offline
                  S Offline
                  SortaCore
                  wrote on last edited by
                  #28

                  No no, it's Windows 8.1 now... At least they're bright enough to realise 8 -> 8.1 should be a free upgrade.

                  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[^]

                    S Offline
                    S Offline
                    Stefan_Lang
                    wrote on last edited by
                    #29

                    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 B 2 Replies 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)

                      S Offline
                      S Offline
                      Stefan_Lang
                      wrote on last edited by
                      #30

                      Easy: introduce a flag indicating when you're done processing (for whatever reason). You can either add that flag to the breaking condition of control statements, or add a single additional nesting layer inquiring the state of that flag everytime you're about to do some more processing (that could be skipped). I've been using that concept successfully for a long time in legacy applications that have lots of very long functions with very high nesting levels. This method at most adds one nesting level, if at all, and it helps keeping track of stuff I need to clean up at various nesting levels before actually exiting the function.

                      OriginalGriffO 1 Reply Last reply
                      0
                      • S Stefan_Lang

                        Easy: introduce a flag indicating when you're done processing (for whatever reason). You can either add that flag to the breaking condition of control statements, or add a single additional nesting layer inquiring the state of that flag everytime you're about to do some more processing (that could be skipped). I've been using that concept successfully for a long time in legacy applications that have lots of very long functions with very high nesting levels. This method at most adds one nesting level, if at all, and it helps keeping track of stuff I need to clean up at various nesting levels before actually exiting the function.

                        OriginalGriffO Offline
                        OriginalGriffO Offline
                        OriginalGriff
                        wrote on last edited by
                        #31

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

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

                        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                        S R 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[^]

                          B Offline
                          B Offline
                          BotReject
                          wrote on last edited by
                          #32

                          It depends. There are times when it is necessary to exit as soon as a decision is reached, as I expect the performance of foreach to be O(n). For example, if a function is trying to find the first prime number within an array then you need to exit as soon as the condition is true, otherwise much time may be wasted. In the example given it depends how large I expect the string array to be, clearly the function itself can potentially take a string array of any size so method 1 seems preferable to me. However, if you don't like multiple return points then use 'break'. A more complex function is often clearer to read and debug if there is only one return point, and this is preferable if speed is not an issue. For example, if a function decides which way a bug is going to turn - left or right, then it may test many conditions, none of which may involve operations on large collections. In this example, it is probably preferable to have only a single return point.

                          1 Reply Last reply
                          0
                          • R Ron Beyer

                            I'm a fan of early exit, so I'd go with the first one (assuming that's what this post is about). It doesn't really matter much in smaller routines like the one above, but when you have longer ones it can be difficult to follow retValue around the function to find out where you are really setting the return value. The first method is shorter because you can run a case through in your head without having to write down variables. I think the question boils down to Early Exit versus Single Exit. There's a lot of debate on the merits of both so I think your answers are going to be somewhat distributed between them. I've yet to hear a debate for single exit that I agree with over the merits of early exit...

                            A Offline
                            A Offline
                            AJC Software
                            wrote on last edited by
                            #33

                            I think an early exit is always best. If you don't have an early exit this can often lead to more nesting later on in the method to allow you to skip the rest of it and unessassary nesting leads to more complicated code. (You could argue that you should splt the method up in this case but I say keep logical units together.)

                            1 Reply Last reply
                            0
                            • N Nicholas Marty

                              I also go mostly for early exit. This helps to keep the code to the left as much as possible. Besides. if a method gets too long... you're doing it wrong ;)

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

                              as per nasa specs, 60 lines on the most extreme atomic task, 15 for anything else.

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

                              Z 1 Reply Last reply
                              0
                              • C CodeHawkz

                                First of all, the second code should have a 'break' as follows. Otherwise, it just continues to loop pointlessly, even if it find "ABC" in the first item.

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

                                Personally, I choose the this method over your first method, since it has a single point of return to the method. About the performance, both versions should be identical as this method would only execute 2 steps extra.

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

                                yours is the most sensible way to handle a single exit.

                                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
                                • 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[^]

                                  K Offline
                                  K Offline
                                  Kenworth71
                                  wrote on last edited by
                                  #36

                                  Don't mind.

                                  1 Reply Last reply
                                  0
                                  • S Simon ORiordan from UK

                                    Code 1 would be my preference as it is the default indentation model for Visual Studio. I don't see the point of re-setting the default model or turning off the auto-complete for the sake of a preference; I find that the usual combination of indents provides a readable and fast coding format which is pretty good at revealing errors and incomplete blocks due to items not aligning conventionally. In other words, you can pick up errors in peripheral vision, which is quick.

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

                                    he was talking about the exit model of the method, the indentation is just a incedent due to the html pasting.

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

                                    S 1 Reply Last reply
                                    0
                                    • S Sentenryu

                                      he was talking about the exit model of the method, the indentation is just a incedent due to the html pasting.

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

                                      S Offline
                                      S Offline
                                      Simon ORiordan from UK
                                      wrote on last edited by
                                      #38

                                      He didn't talk about anything. He simply presented code and asked for preferences.

                                      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)

                                        S Offline
                                        S Offline
                                        Stefan_Lang
                                        wrote on last edited by
                                        #39

                                        ... 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 P 2 Replies Last reply
                                        0
                                        • S Sentenryu

                                          as per nasa specs, 60 lines on the most extreme atomic task, 15 for anything else.

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

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

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