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. Multiple returns from methods or clean code flow

Multiple returns from methods or clean code flow

Scheduled Pinned Locked Moved The Lounge
questiondiscussioncryptographycollaborationhelp
85 Posts 40 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.
  • M megaadam

    I thought you were joking when you said Whitesmiths!

    for()
    {
    for()

    Really hurts my eyes :sigh:

    for()
    {
    for()

    I like.

    "If we don't change direction, we'll end up where we're going"

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

    You are welcome to your opinion*, but I like the way it's consistent: the indentation is the whole of the relevant block of code:

    if (a)
    b;

    if (a)
    {
    b;
    c;
    }

    Instead of the inconsistent Allman:

    if (a)
    b;

    if (a)
    {
    b;
    c;
    }

    * As long as your opinion doesn't include using 1TB, of course.

    Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

    "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

    M 1 Reply Last reply
    0
    • F Forogar

      I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

      void SomeFunction(SomeThing s)
      {
      if (s != null)
      {
      if (s.Thing != null)
      {
      // Do Some Process with s.Thing
      .
      .
      .
      }
      }
      }

      becomes:

      void SomeFunction(SomeThing s)
      {
      if (s == null) return
      if (s.Thing == null) return;
      // Do Some Process with s.Thing
      .
      .
      .
      }

      This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

      void SomeFunction(SomeThing s)
      {
      if (s != null && s.Thing != null)
      {
      // Do Some Process with s.Thing
      .
      .
      .
      }
      }

      or possibly:

      void SomeFunction(SomeThing s)
      {
      if (s?.Thing != null)
      {
      // Do Some Process with s.Thing
      .
      .
      .
      }
      }

      Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

      - I would love to change the world, but they won’t give me the source code.

      K Offline
      K Offline
      kalberts
      wrote on last edited by
      #53

      Years ago I was working with people who insisted on single point of return and single loop termination, with no exception whatsoever. Both continue and break out of loops were "forbidden". These were also people who insisted on putting opening and closing braces on separate lines, and always enclose the body of an if in braces, even a single assignment (so the minimum line count for an if statement was four, eight lines for an if/else). In some code, opening and closing braces made up at least a third of the code lines. I guess that made me stall. I got sick of vading through jungles and fords of little more than braces. Finding the end of a loop, or even a function, required you to leaf through pages by pages of code with minimal information content. In my first programming course, one basic principle was taught: Always fit a function in a single page, so that you can overview all of it. Obviously, the main message was to choose a suitable abstraction level and factor out common sub-operations, but if an if/else costs you a minimum of eight lines, you can't build much abstraction (for the next level) in a single page! So I use breaks, continues and returns, to keep the function logic together, not spread over multiple pages / screenfuls. If you immediately see where the loop ends, or you have all the returns on a single page, you will easily manage it. If you like to water out your code with tons of braces and elses and umpteen nesting levels, then you loose control over your returns. But that is exactly what returns and continues and breaks are meant to avoid.

      1 Reply Last reply
      0
      • D Delphi 7 Solutions

        I think that the Return statement should be dropped in any language, for example look at Delphi (object pascal) they did not have a return statement until recently it seems. A function had to fill up a variable called Result, and because there was no return statement developers where forced to maintain a clean flow. This is how it should be everywhere IMHO

        K Offline
        K Offline
        kalberts
        wrote on last edited by
        #54

        The first person to use the term "clean flow" has the definition right to the term :-) My experience is that prohibiting return (and continue and break) easily ruins that "clean flow". The clean flow should be for the normal, standard, expected behaviour. If something unexpected occurs, or some special case appears, you should handle it (as far as required) and get out of there! You shouldn't clutter up the rest of the function code with error flags and statuses pertaining to a special condition that was handled much higher up, serving only to skip the rest of the function code. That messes up the rest of the function code. "Then you should raise an exception", some says. That's just another way of returning prematurely; it does not ensure a single point of exit. Besides, the situation is not necessarity exceptional, it may be simply detecting that there is nothing more to be done. Program flow by exceptions is certainly no clean code flow.

        D 1 Reply Last reply
        0
        • F Forogar

          I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

          void SomeFunction(SomeThing s)
          {
          if (s != null)
          {
          if (s.Thing != null)
          {
          // Do Some Process with s.Thing
          .
          .
          .
          }
          }
          }

          becomes:

          void SomeFunction(SomeThing s)
          {
          if (s == null) return
          if (s.Thing == null) return;
          // Do Some Process with s.Thing
          .
          .
          .
          }

          This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

          void SomeFunction(SomeThing s)
          {
          if (s != null && s.Thing != null)
          {
          // Do Some Process with s.Thing
          .
          .
          .
          }
          }

          or possibly:

          void SomeFunction(SomeThing s)
          {
          if (s?.Thing != null)
          {
          // Do Some Process with s.Thing
          .
          .
          .
          }
          }

          Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

          - I would love to change the world, but they won’t give me the source code.

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

          Forogar wrote:

          This caused horribly messy code

          Nah. Earlier return is both much more readable and more logical too. More readable: you don't have to skip around when following a given execution path, you just follow it to its return. More logical: you don't have to keep anything you don't need anymore in mind. When the function is done with it, it's returned and doesn't add to the cognitive load anymore. The time when single exit point was a 'good practice' was, IIRC, during the structured programming days, as an antidote to goto statements.

          Forogar wrote:

          introduces an execution statement (return) on the same line as the "if" which is bad coding practice

          Huh? why? It's only styling. I would avoid having it under the if without brackets, because that's confusing sometimes, but on the same line? No problems.

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            Under most circumstances, a single return is best. But ... I much prefer this:

            void MyFunc ()
            {
            if (!ValidateUserInput(ATextBox.Text))
            {
            TellUserAboutTheProblem();
            return;
            }
            if (!ValidateUserInput(AnotherTextBox.Text))
            {
            TellUserAboutTheProblem();
            return;
            }
            ...
            }

            To this:

            void MyFunc ()
            {
            if (!ValidateUserInput(ATextBox.Text))
            {
            TellUserAboutTheProblem();
            }
            else if (!ValidateUserInput(AnotherTextBox.Text))
            {
            TellUserAboutTheProblem();
            }
            else
            {
            ...
            }
            }

            And sometimes the best thing to do is just return, particularly from a nested loop:

            for (int i = 0; i < 100; i++)
            {
            for (int j = 0; j < 100; j++)
            {
            if (myArray[i, j] == value) return true;
            }
            }
            return false;

            Any other mechanism is just making it more complicated, not less.

            Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

            M Offline
            M Offline
            milo xml
            wrote on last edited by
            #56

            OriginalGriff wrote:

            void MyFunc () { if (!ValidateUserInput(ATextBox.Text)) { TellUserAboutTheProblem(); } else if (!ValidateUserInput(AnotherTextBox.Text)) { TellUserAboutTheProblem(); } else { ... } }

            One of my first program was this. Luckily I started coming here and learned how to do it better :)

            1 Reply Last reply
            0
            • F Forogar

              I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

              void SomeFunction(SomeThing s)
              {
              if (s != null)
              {
              if (s.Thing != null)
              {
              // Do Some Process with s.Thing
              .
              .
              .
              }
              }
              }

              becomes:

              void SomeFunction(SomeThing s)
              {
              if (s == null) return
              if (s.Thing == null) return;
              // Do Some Process with s.Thing
              .
              .
              .
              }

              This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

              void SomeFunction(SomeThing s)
              {
              if (s != null && s.Thing != null)
              {
              // Do Some Process with s.Thing
              .
              .
              .
              }
              }

              or possibly:

              void SomeFunction(SomeThing s)
              {
              if (s?.Thing != null)
              {
              // Do Some Process with s.Thing
              .
              .
              .
              }
              }

              Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

              - I would love to change the world, but they won’t give me the source code.

              M Offline
              M Offline
              Michael Breeden
              wrote on last edited by
              #57

              I have developed c, C++, C# SW for decades. I believe that when an exception occurs, not only must it identify where and what went wrong, but if possible, how to fix it and who to blame. In a recent conversation, my opposite number who has decades of experience pointed out a way to handle this situation in the complicated code we use. Use a goto statement. It is only used within the body of a method and only to take you to the end of the method. It solves a ton of problems with flow and retaining error information. In my past decades of development, I've only used the goto statement once (gotoxy many times :)) I plan to use it much more... ONLY WITHIN A METHOD THOUGH!

              1 Reply Last reply
              0
              • D Delphi 7 Solutions

                I think that the Return statement should be dropped in any language, for example look at Delphi (object pascal) they did not have a return statement until recently it seems. A function had to fill up a variable called Result, and because there was no return statement developers where forced to maintain a clean flow. This is how it should be everywhere IMHO

                Richard DeemingR Offline
                Richard DeemingR Offline
                Richard Deeming
                wrote on last edited by
                #58

                Automatically vetoing that idea, because that's what VB6 did! :laugh: If you're desperate, VB.NET still allows it: To return a value using Exit Function or End Function | How to: Return a Value from a Procedure (Visual Basic) | Microsoft Docs[^]


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  You are welcome to your opinion*, but I like the way it's consistent: the indentation is the whole of the relevant block of code:

                  if (a)
                  b;

                  if (a)
                  {
                  b;
                  c;
                  }

                  Instead of the inconsistent Allman:

                  if (a)
                  b;

                  if (a)
                  {
                  b;
                  c;
                  }

                  * As long as your opinion doesn't include using 1TB, of course.

                  Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                  M Offline
                  M Offline
                  megaadam
                  wrote on last edited by
                  #59

                  I have been brainwashed to NEVER do:

                  if (a)
                  b;

                  I think the preference is a matter of taste. I don't find either alternative more "consistent". "Consistent" depends on how you define that word (and the words "relevant code"). When skimming over large blocks of code the braces are - for my eyes - easier to find Allman style. And the b; is very slightly easier on my eye in your Allman example. My guess is that we prefer what we were exposed to when we started walking... coding...

                  "If we don't change direction, we'll end up where we're going"

                  A 1 Reply Last reply
                  0
                  • F Forogar

                    I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                    void SomeFunction(SomeThing s)
                    {
                    if (s != null)
                    {
                    if (s.Thing != null)
                    {
                    // Do Some Process with s.Thing
                    .
                    .
                    .
                    }
                    }
                    }

                    becomes:

                    void SomeFunction(SomeThing s)
                    {
                    if (s == null) return
                    if (s.Thing == null) return;
                    // Do Some Process with s.Thing
                    .
                    .
                    .
                    }

                    This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                    void SomeFunction(SomeThing s)
                    {
                    if (s != null && s.Thing != null)
                    {
                    // Do Some Process with s.Thing
                    .
                    .
                    .
                    }
                    }

                    or possibly:

                    void SomeFunction(SomeThing s)
                    {
                    if (s?.Thing != null)
                    {
                    // Do Some Process with s.Thing
                    .
                    .
                    .
                    }
                    }

                    Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                    - I would love to change the world, but they won’t give me the source code.

                    P Offline
                    P Offline
                    Peter R Fletcher
                    wrote on last edited by
                    #60

                    I use 'early' returns only to handle errors (typically input or 'no data' errors that don't merit throwing an exception) where the function is returning some sort of null value or an error code.

                    1 Reply Last reply
                    0
                    • K kalberts

                      The first person to use the term "clean flow" has the definition right to the term :-) My experience is that prohibiting return (and continue and break) easily ruins that "clean flow". The clean flow should be for the normal, standard, expected behaviour. If something unexpected occurs, or some special case appears, you should handle it (as far as required) and get out of there! You shouldn't clutter up the rest of the function code with error flags and statuses pertaining to a special condition that was handled much higher up, serving only to skip the rest of the function code. That messes up the rest of the function code. "Then you should raise an exception", some says. That's just another way of returning prematurely; it does not ensure a single point of exit. Besides, the situation is not necessarity exceptional, it may be simply detecting that there is nothing more to be done. Program flow by exceptions is certainly no clean code flow.

                      D Offline
                      D Offline
                      Delphi 7 Solutions
                      wrote on last edited by
                      #61

                      Not sure what you mean I never had to uses error flags and statuses for anything like this. In my experience prohibiting return (and continue and break) never ruined that "clean flow" but always improved it. And without using stuff like ugly flags and statuses. In our coding guidelines the return is prohibited, and since this was introduced we saw the time needed for maintenance and bugfixing dropped noticable. And yes, exceptions are not to be used for program flow, that is very true.

                      1 Reply Last reply
                      0
                      • F Forogar

                        I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                        void SomeFunction(SomeThing s)
                        {
                        if (s != null)
                        {
                        if (s.Thing != null)
                        {
                        // Do Some Process with s.Thing
                        .
                        .
                        .
                        }
                        }
                        }

                        becomes:

                        void SomeFunction(SomeThing s)
                        {
                        if (s == null) return
                        if (s.Thing == null) return;
                        // Do Some Process with s.Thing
                        .
                        .
                        .
                        }

                        This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                        void SomeFunction(SomeThing s)
                        {
                        if (s != null && s.Thing != null)
                        {
                        // Do Some Process with s.Thing
                        .
                        .
                        .
                        }
                        }

                        or possibly:

                        void SomeFunction(SomeThing s)
                        {
                        if (s?.Thing != null)
                        {
                        // Do Some Process with s.Thing
                        .
                        .
                        .
                        }
                        }

                        Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                        - I would love to change the world, but they won’t give me the source code.

                        O Offline
                        O Offline
                        obermd
                        wrote on last edited by
                        #62

                        When multiple returns reduce the nesting inside a module they make a lot of sense (as well as making the code more readable in my opinion). This is similar to using the && and || conditionals that only evaluation clauses as needed.

                        1 Reply Last reply
                        0
                        • M megaadam

                          I have been brainwashed to NEVER do:

                          if (a)
                          b;

                          I think the preference is a matter of taste. I don't find either alternative more "consistent". "Consistent" depends on how you define that word (and the words "relevant code"). When skimming over large blocks of code the braces are - for my eyes - easier to find Allman style. And the b; is very slightly easier on my eye in your Allman example. My guess is that we prefer what we were exposed to when we started walking... coding...

                          "If we don't change direction, we'll end up where we're going"

                          A Offline
                          A Offline
                          Andre Pereira
                          wrote on last edited by
                          #63

                          Quote:

                          I have been brainwashed to NEVER do: if (a) b;

                          Good for you, you are ready to avoid a billion dollar bug because "I don't need braces or consistent rules".

                          1 Reply Last reply
                          0
                          • L Lost User

                            sort of depends on what I call the "story" if the story says "if X is null or is [example] an empty list then stop processing" = in my mind early return. if the story says "do thus-ad-that to the contents of X" - to save on errors naturally check X for null/empty makes sense - then of course it's if (X != null) ...

                            Forogar wrote:

                            ntroduces an execution statement (return) on the same line as the "if" which is bad coding practice

                            ?????????????? bad coding practice ????????????????? huh? Nothing is wrong, nor bad, nor unsafe with that code, it is perfectly good code. you confuse practice with style: style is subjective, "bad practice" increases the chance for error or failure. personally I dislike code that runs too many pages, so I often put short single statements and opening braces on the same line as the if (), while () etc. (Coming from K&R style C background.) and I like .... AND SO, before you say it, I'll say it for you: --- you think my style is ugly. Well guess what: ---- I think your style is ugly. AND WHO CARES!! 1. it's the code that matters, NOT THE STYLE, 2. different style IS NOT BAD PRACTICE weather you like it or not. (please don't bring up "readability" bullshit, I find more compact more readable, please don't bring up "industry standard" - my K&R background, and I'm not the only one doing it that way.) 3. you can have the editor re-format [to your preferred] style on one keystroke, so even more WHO CARES. nuff said.

                            Message Signature (Click to edit ->)

                            A Offline
                            A Offline
                            Andre Pereira
                            wrote on last edited by
                            #64

                            If you have dealt with Unix fanboys, you'll now doubt have encountered the stupid "which hacky character shall we use for white space: spaces or tabs?". The correct answer is "whatever the team is using, I format it to that before committing". As for consistency, I only really am a stickler with fucking braces. I've seen too many recurrent bugs because a programmer is cute and makes a braceless if. Then the next one comes in, adds one more call and doesn't realise the braces are gone. Ooops, billion dollar bug introduced. Nasty and no need.

                            L 1 Reply Last reply
                            0
                            • F Forogar

                              I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                              void SomeFunction(SomeThing s)
                              {
                              if (s != null)
                              {
                              if (s.Thing != null)
                              {
                              // Do Some Process with s.Thing
                              .
                              .
                              .
                              }
                              }
                              }

                              becomes:

                              void SomeFunction(SomeThing s)
                              {
                              if (s == null) return
                              if (s.Thing == null) return;
                              // Do Some Process with s.Thing
                              .
                              .
                              .
                              }

                              This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                              void SomeFunction(SomeThing s)
                              {
                              if (s != null && s.Thing != null)
                              {
                              // Do Some Process with s.Thing
                              .
                              .
                              .
                              }
                              }

                              or possibly:

                              void SomeFunction(SomeThing s)
                              {
                              if (s?.Thing != null)
                              {
                              // Do Some Process with s.Thing
                              .
                              .
                              .
                              }
                              }

                              Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                              - I would love to change the world, but they won’t give me the source code.

                              S Offline
                              S Offline
                              SpiritualMadMan
                              wrote on last edited by
                              #65

                              For me, as a novice, my first concern is can I read and understand the code after a good nights rest. After I get it running, then look for ways to make it better. Of course VS2017 does a lot for me. I use inline returns all the time for avoiding null errors when getting data from a DataGridView. But, for compound conditions it depends on what I am doing and whether they can be easily combined. As for the final version with the "?" for me that obfuscates what is happening. But, then I am a novice. In this case I would probably settle on the next to last version.

                              1 Reply Last reply
                              0
                              • F Forogar

                                I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                                void SomeFunction(SomeThing s)
                                {
                                if (s != null)
                                {
                                if (s.Thing != null)
                                {
                                // Do Some Process with s.Thing
                                .
                                .
                                .
                                }
                                }
                                }

                                becomes:

                                void SomeFunction(SomeThing s)
                                {
                                if (s == null) return
                                if (s.Thing == null) return;
                                // Do Some Process with s.Thing
                                .
                                .
                                .
                                }

                                This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                                void SomeFunction(SomeThing s)
                                {
                                if (s != null && s.Thing != null)
                                {
                                // Do Some Process with s.Thing
                                .
                                .
                                .
                                }
                                }

                                or possibly:

                                void SomeFunction(SomeThing s)
                                {
                                if (s?.Thing != null)
                                {
                                // Do Some Process with s.Thing
                                .
                                .
                                .
                                }
                                }

                                Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                                - I would love to change the world, but they won’t give me the source code.

                                M Offline
                                M Offline
                                Martin ISDN
                                wrote on last edited by
                                #66

                                i would go ether way for what produces smaller and simpler code. since this is a trivial example it is difficult to speak in general. in this case i wouldn't go for No.1 it's against my taste, but No.2, No.3 and No.4 are OK. No.2 and No.3 seem to have a different philosophy but they do exactly the same thing, imminent return if s == null. i think No.2 is the way assembly coder would see the situation and No.1 would be how a Pascal programmer sees it. structured style programmers would go for a one exit routine, but sometimes that makes code especially complicated.

                                1 Reply Last reply
                                0
                                • C CodeWraith

                                  Urban Cricket wrote:

                                  John Carmack uses early returns.

                                  Looking at my bookshelf: The Graphics Programming Black Book, by Michael Abrash and with a foreword by John Carmack. Fearsomely thick tome, full of how to write fast graphics code. That kind of processor cycle counting on a 386 or 486 is outdated, while the algorithmic optimizations remain as current as ever, especially if you are able to delegate them to the graphics processor. Early returns as a way to waste no processor cycle too much in a function is only rarely important anymore.

                                  I have lived with several Zen masters - all of them were cats. His last invention was an evil Lasagna. It didn't kill anyone, and it actually tasted pretty good.

                                  S Offline
                                  S Offline
                                  sasadler
                                  wrote on last edited by
                                  #67

                                  Unless you're an embedded developer trying to squeak out the quickest code on an underpowered processor. I was always getting projects with weenie processors and grandiose firmware requirements. It seems that the hardware engineer had a rather limited grasp on firmware development and how much space/speed would be required for the project. They eventually figured out that I should be involved in the processor and memory requirements selection.

                                  C 1 Reply Last reply
                                  0
                                  • F Forogar

                                    I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                                    void SomeFunction(SomeThing s)
                                    {
                                    if (s != null)
                                    {
                                    if (s.Thing != null)
                                    {
                                    // Do Some Process with s.Thing
                                    .
                                    .
                                    .
                                    }
                                    }
                                    }

                                    becomes:

                                    void SomeFunction(SomeThing s)
                                    {
                                    if (s == null) return
                                    if (s.Thing == null) return;
                                    // Do Some Process with s.Thing
                                    .
                                    .
                                    .
                                    }

                                    This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                                    void SomeFunction(SomeThing s)
                                    {
                                    if (s != null && s.Thing != null)
                                    {
                                    // Do Some Process with s.Thing
                                    .
                                    .
                                    .
                                    }
                                    }

                                    or possibly:

                                    void SomeFunction(SomeThing s)
                                    {
                                    if (s?.Thing != null)
                                    {
                                    // Do Some Process with s.Thing
                                    .
                                    .
                                    .
                                    }
                                    }

                                    Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                                    - I would love to change the world, but they won’t give me the source code.

                                    T Offline
                                    T Offline
                                    TylerMc007
                                    wrote on last edited by
                                    #68

                                    I would argue there is no “one way”. When it makes sense use an early return, then do so. The problem I so often see is both methods are used poorly. Programmers use embedded return statements when they should be throwing and catching errors, or they will have one method which has five different returns (bad). Or they use 5 tier “if” statements which is usually an indication that they may need to refactor code, maybe use function overloading or polymorphic behavior. In my opinion, programming is as much art as it is science, knowing when to apply the rules and when not to.

                                    1 Reply Last reply
                                    0
                                    • S sasadler

                                      Unless you're an embedded developer trying to squeak out the quickest code on an underpowered processor. I was always getting projects with weenie processors and grandiose firmware requirements. It seems that the hardware engineer had a rather limited grasp on firmware development and how much space/speed would be required for the project. They eventually figured out that I should be involved in the processor and memory requirements selection.

                                      C Offline
                                      C Offline
                                      CodeWraith
                                      wrote on last edited by
                                      #69

                                      I sure know that. My first computer had a hex keyboard and actually was very much like today's microcontrollers. And I still have it and use it, just to stay sharp. Edit: Picture[^]

                                      I have lived with several Zen masters - all of them were cats. His last invention was an evil Lasagna. It didn't kill anyone, and it actually tasted pretty good.

                                      S 1 Reply Last reply
                                      0
                                      • C CodeWraith

                                        Mark_Wallace wrote:

                                        Save your processor a billionth of a second of effort

                                        Depending on the processor and the stack protocol you use to pass parameters and return values, you may find that you gain little to nothing. Been there recently when I had to modify the 'traditional' call protocol of my old computer. Now it uses a second stack to pass parameters and return values, instead of inlining the parameters with the code for the call. Yuck, was way to close to self modifying code!. And I extended the address of the subroutine to 24 bits, so that I now can do bank switching in the calling protocol and call code anywhere in a 16 Mb memory space without the processor noticing anything. Not bad for a 40 year old 8 bit computer. If only there was a convenient way to access data anywhere in that memory space as well.

                                        I have lived with several Zen masters - all of them were cats. His last invention was an evil Lasagna. It didn't kill anyone, and it actually tasted pretty good.

                                        M Offline
                                        M Offline
                                        Mark_Wallace
                                        wrote on last edited by
                                        #70

                                        :thumbsup: Sounds like my kind of toy!

                                        I wanna be a eunuchs developer! Pass me a bread knife!

                                        1 Reply Last reply
                                        0
                                        • F Forogar

                                          I have just had a heated argument cage fight lively discussion with some of my team members about ReSharper's suggestion of refactoring code to replace nested ifs with a series of multiple early return statements. This caused horribly messy code that ReSharper actually described in it's help as "more readable"! Using a version of their example code (which is a lot simpler than the actual code in question):

                                          void SomeFunction(SomeThing s)
                                          {
                                          if (s != null)
                                          {
                                          if (s.Thing != null)
                                          {
                                          // Do Some Process with s.Thing
                                          .
                                          .
                                          .
                                          }
                                          }
                                          }

                                          becomes:

                                          void SomeFunction(SomeThing s)
                                          {
                                          if (s == null) return
                                          if (s.Thing == null) return;
                                          // Do Some Process with s.Thing
                                          .
                                          .
                                          .
                                          }

                                          This makes a complete hash of the natural flow of the code and introduces an execution statement (return) on the same line as the "if" which is bad coding practice, and then does it again, and then drops though to do some actual processing. If I was to refactor the code it would do this:

                                          void SomeFunction(SomeThing s)
                                          {
                                          if (s != null && s.Thing != null)
                                          {
                                          // Do Some Process with s.Thing
                                          .
                                          .
                                          .
                                          }
                                          }

                                          or possibly:

                                          void SomeFunction(SomeThing s)
                                          {
                                          if (s?.Thing != null)
                                          {
                                          // Do Some Process with s.Thing
                                          .
                                          .
                                          .
                                          }
                                          }

                                          Which is a lot cleaner! ...and this isn't even considering a method that returns a value of some sort. Opinions?

                                          - I would love to change the world, but they won’t give me the source code.

                                          M Offline
                                          M Offline
                                          MSBassSinger
                                          wrote on last edited by
                                          #71

                                          One way into a method, one way out (not counting ref and out parameters, which are intuitively obvious). After 40+ years in software development, my tolerance for lazy programmers that just want to hack up some code and get the minimum done with the least time - is very low. Some software shops are starting to use an approach I have used for years when I hired developers. Instead of hiring 10 "full stack" developers with an eye to cheap labor, H1-B and other inexperienced programmers cranking out poor code that just barely works for today, they take a different road. For those 10 positions, they hire 6 experienced software engineers that understand how to code for value engineering, supportability, likely future needs, performance, readability, and meaningful comments. A 7th junior developer is hired who has an attitude and willingness to learn from the senior developers - a person whose character is teachable. No H1-B's. The end result is better code, faster development cycles, fewer bugs, and lower life cycle cost. Experienced software engineers understand how incredibly sophomoric it is to have multiple returns. Now get off my lawn! :)

                                          B 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