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 Insider News
  4. Avoid else, return early

Avoid else, return early

Scheduled Pinned Locked Moved The Insider News
com
20 Posts 10 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.
  • K Kent Sharkey

    Tim Oxley[^]:

    Return as soon as you know your method cannot do any more meaningful work

    Returning this one before even looking at the if statement

    Or: discuss

    N Offline
    N Offline
    Nemanja Trifunovic
    wrote on last edited by
    #2

    "else" considered harmful :-D

    utf8-cpp

    K 1 Reply Last reply
    0
    • N Nemanja Trifunovic

      "else" considered harmful :-D

      utf8-cpp

      K Offline
      K Offline
      Kent Sharkey
      wrote on last edited by
      #3

      Dammit, how did I miss that one? :thumbsup:

      TTFN - Kent

      1 Reply Last reply
      0
      • K Kent Sharkey

        Tim Oxley[^]:

        Return as soon as you know your method cannot do any more meaningful work

        Returning this one before even looking at the if statement

        Or: discuss

        B Offline
        B Offline
        BillWoodruff
        wrote on last edited by
        #4

        What else is ambiguous about "else" ?

        «... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12

        1 Reply Last reply
        0
        • K Kent Sharkey

          Tim Oxley[^]:

          Return as soon as you know your method cannot do any more meaningful work

          Returning this one before even looking at the if statement

          Or: discuss

          T Offline
          T Offline
          Tim Carmichael
          wrote on last edited by
          #5

          The whole thought of processing the exception first upon returning from a call is so counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers. When I read the code, I think the developer is expecting an error so prepares to handle it first. It all goes back to the maxim: write clean code; there is nothing wrong with indentation or else statements. Also, write comments on what the process is doing and why, don't assume the code is so well written its intuitively obvious what the desired result is.

          T R D 3 Replies Last reply
          0
          • K Kent Sharkey

            Tim Oxley[^]:

            Return as soon as you know your method cannot do any more meaningful work

            Returning this one before even looking at the if statement

            Or: discuss

            T Offline
            T Offline
            TheGreatAndPowerfulOz
            wrote on last edited by
            #6

            if (Agree())
            {
            return true;
            }
            else
            {
            return false;
            }

            or

            return Agree();

            #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

            1 Reply Last reply
            0
            • T Tim Carmichael

              The whole thought of processing the exception first upon returning from a call is so counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers. When I read the code, I think the developer is expecting an error so prepares to handle it first. It all goes back to the maxim: write clean code; there is nothing wrong with indentation or else statements. Also, write comments on what the process is doing and why, don't assume the code is so well written its intuitively obvious what the desired result is.

              T Offline
              T Offline
              TheGreatAndPowerfulOz
              wrote on last edited by
              #7

              Tim Carmichael wrote:

              process is doing and why

              Agree with the why. I can read the code to see what it's doing. I've seen so many comments // declare variables then // call the function then // process result So helpful.

              Tim Carmichael wrote:

              there is nothing wrong with indentation or else statements

              egregious indentation and if/else's are problems when there are too many levels, usually more than two. This leads to functions that are too long and have multiple purposes. Better to refactor the code and move the different cases into different functions.

              #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

              T 1 Reply Last reply
              0
              • T TheGreatAndPowerfulOz

                Tim Carmichael wrote:

                process is doing and why

                Agree with the why. I can read the code to see what it's doing. I've seen so many comments // declare variables then // call the function then // process result So helpful.

                Tim Carmichael wrote:

                there is nothing wrong with indentation or else statements

                egregious indentation and if/else's are problems when there are too many levels, usually more than two. This leads to functions that are too long and have multiple purposes. Better to refactor the code and move the different cases into different functions.

                #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                T Offline
                T Offline
                Tim Carmichael
                wrote on last edited by
                #8

                TheGreatAndPowerfulOz wrote:

                Better to refactor the code and move the different cases into different functions.

                I absolutely agree with this... The worst If/Then block I ever had to write was in Fortran for some equipment routing in an automated factory. The 'If' statement was 23 lines - and that is just the 'If' portion, not the code executed if the statement was true. I had a block of comments preceding it explaining what it was doing and why with a warning that 'if you break it, you get to maintain it'. But, if was an if/then/else block to determine an action; it wasn't multiple nested blocks within each other.

                T R 2 Replies Last reply
                0
                • T Tim Carmichael

                  TheGreatAndPowerfulOz wrote:

                  Better to refactor the code and move the different cases into different functions.

                  I absolutely agree with this... The worst If/Then block I ever had to write was in Fortran for some equipment routing in an automated factory. The 'If' statement was 23 lines - and that is just the 'If' portion, not the code executed if the statement was true. I had a block of comments preceding it explaining what it was doing and why with a warning that 'if you break it, you get to maintain it'. But, if was an if/then/else block to determine an action; it wasn't multiple nested blocks within each other.

                  T Offline
                  T Offline
                  TheGreatAndPowerfulOz
                  wrote on last edited by
                  #9

                  ugh. I feel the pain just reading that.

                  #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                  1 Reply Last reply
                  0
                  • K Kent Sharkey

                    Tim Oxley[^]:

                    Return as soon as you know your method cannot do any more meaningful work

                    Returning this one before even looking at the if statement

                    Or: discuss

                    J Offline
                    J Offline
                    Joe Woodbury
                    wrote on last edited by
                    #10

                    I tend to favor single returns for debugging reasons, if it doesn't result in absurd code. However, quite often it results in code that is more clear.

                    1 Reply Last reply
                    0
                    • T Tim Carmichael

                      The whole thought of processing the exception first upon returning from a call is so counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers. When I read the code, I think the developer is expecting an error so prepares to handle it first. It all goes back to the maxim: write clean code; there is nothing wrong with indentation or else statements. Also, write comments on what the process is doing and why, don't assume the code is so well written its intuitively obvious what the desired result is.

                      R Offline
                      R Offline
                      realJSOP
                      wrote on last edited by
                      #11

                      Tim Carmichael wrote:

                      counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers.

                      It's a mixed bag for me. I prefer to exit a method as early as possible, when it makes sense (performing sanity checks on method parameters to ensure they're not null at the top of the method, and throw argument exceptions if they don't meet expected values). After that, I let code go where it needs to go, letting the "true" conditions happen first, and let else handle the "false" conditions.. In the end, I also strive to have a single point of exit instead of having multiple returns sprinkled throughout a method.

                      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                      -----
                      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                      -----
                      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                      T D 2 Replies Last reply
                      0
                      • T Tim Carmichael

                        TheGreatAndPowerfulOz wrote:

                        Better to refactor the code and move the different cases into different functions.

                        I absolutely agree with this... The worst If/Then block I ever had to write was in Fortran for some equipment routing in an automated factory. The 'If' statement was 23 lines - and that is just the 'If' portion, not the code executed if the statement was true. I had a block of comments preceding it explaining what it was doing and why with a warning that 'if you break it, you get to maintain it'. But, if was an if/then/else block to determine an action; it wasn't multiple nested blocks within each other.

                        R Offline
                        R Offline
                        realJSOP
                        wrote on last edited by
                        #12

                        I once encountered a method that was over 1000 lines long. :/

                        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                        -----
                        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                        -----
                        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                        1 Reply Last reply
                        0
                        • K Kent Sharkey

                          Tim Oxley[^]:

                          Return as soon as you know your method cannot do any more meaningful work

                          Returning this one before even looking at the if statement

                          Or: discuss

                          D Offline
                          D Offline
                          Dominic Burford
                          wrote on last edited by
                          #13

                          Resharper uses this as one of its built-in rules and will suggest re-writing your code to exit early as the article describes.

                          "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." - C.A.R. Hoare Home | LinkedIn | Google+ | Twitter

                          1 Reply Last reply
                          0
                          • R realJSOP

                            Tim Carmichael wrote:

                            counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers.

                            It's a mixed bag for me. I prefer to exit a method as early as possible, when it makes sense (performing sanity checks on method parameters to ensure they're not null at the top of the method, and throw argument exceptions if they don't meet expected values). After that, I let code go where it needs to go, letting the "true" conditions happen first, and let else handle the "false" conditions.. In the end, I also strive to have a single point of exit instead of having multiple returns sprinkled throughout a method.

                            ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                            -----
                            You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                            -----
                            When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                            T Offline
                            T Offline
                            TheGreatAndPowerfulOz
                            wrote on last edited by
                            #14

                            John Simmons / outlaw programmer wrote:

                            strive to have a single point of exit

                            That can sometimes produce code that looks like an extortionist got hold of it. Here's were some judicious use of goto may be warranted.

                            #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                            R 1 Reply Last reply
                            0
                            • T TheGreatAndPowerfulOz

                              John Simmons / outlaw programmer wrote:

                              strive to have a single point of exit

                              That can sometimes produce code that looks like an extortionist got hold of it. Here's were some judicious use of goto may be warranted.

                              #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                              R Offline
                              R Offline
                              realJSOP
                              wrote on last edited by
                              #15

                              TheGreatAndPowerfulOz wrote:

                              Here's were some judicious use of goto may be warranted.

                              Just say no to goto. I typically define a result variable, and progress through the method setting that variable as appropriate. If I have a longish chain of if/else clauses I indent them like so:

                              int result = 0;
                              if (condition)
                              {
                              }
                              else if (condition)
                              {
                              }
                              ... and so on
                              return result;

                              If conditions are favorable, I'll use a switch statement instead of if/else, but I still try to have only one exit point (exceptions notwithstanding). I also strive to keep my methods short and specific to the process/task described by the name of the method.

                              ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                              -----
                              You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                              -----
                              When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                              T 1 Reply Last reply
                              0
                              • R realJSOP

                                TheGreatAndPowerfulOz wrote:

                                Here's were some judicious use of goto may be warranted.

                                Just say no to goto. I typically define a result variable, and progress through the method setting that variable as appropriate. If I have a longish chain of if/else clauses I indent them like so:

                                int result = 0;
                                if (condition)
                                {
                                }
                                else if (condition)
                                {
                                }
                                ... and so on
                                return result;

                                If conditions are favorable, I'll use a switch statement instead of if/else, but I still try to have only one exit point (exceptions notwithstanding). I also strive to keep my methods short and specific to the process/task described by the name of the method.

                                ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                -----
                                You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                -----
                                When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                T Offline
                                T Offline
                                TheGreatAndPowerfulOz
                                wrote on last edited by
                                #16

                                John Simmons / outlaw programmer wrote:

                                keep my methods short and specific

                                That's the key.

                                #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                                1 Reply Last reply
                                0
                                • T Tim Carmichael

                                  The whole thought of processing the exception first upon returning from a call is so counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers. When I read the code, I think the developer is expecting an error so prepares to handle it first. It all goes back to the maxim: write clean code; there is nothing wrong with indentation or else statements. Also, write comments on what the process is doing and why, don't assume the code is so well written its intuitively obvious what the desired result is.

                                  D Offline
                                  D Offline
                                  Dr Walt Fair PE
                                  wrote on last edited by
                                  #17

                                  Tim Carmichael wrote:

                                  It all goes back to the maxim: write clean code; there is nothing wrong with indentation or else statements. Also, write comments on what the process is doing and why, don't assume the code is so well written its intuitively obvious what the desired result is.

                                  My code is always intuitively obvious, since I intuited it, until the next day, that is!

                                  CQ de W5ALT

                                  Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                                  1 Reply Last reply
                                  0
                                  • K Kent Sharkey

                                    Tim Oxley[^]:

                                    Return as soon as you know your method cannot do any more meaningful work

                                    Returning this one before even looking at the if statement

                                    Or: discuss

                                    S Offline
                                    S Offline
                                    S Douglas
                                    wrote on last edited by
                                    #18

                                    Tim Oxley wrote:

                                    Error handling is noise.

                                    Got it, if a problem occurs then the whole app should die. I wonder if he was part of the team that wrote the usb interface for the windows phone, failure to read and the whole phone reboots.


                                    Common sense is admitting there is cause and effect and that you can exert some control over what you understand.

                                    1 Reply Last reply
                                    0
                                    • R realJSOP

                                      Tim Carmichael wrote:

                                      counter intuitive to the way we think; we process good/expected results first, THEN proceed to look at the outliers.

                                      It's a mixed bag for me. I prefer to exit a method as early as possible, when it makes sense (performing sanity checks on method parameters to ensure they're not null at the top of the method, and throw argument exceptions if they don't meet expected values). After that, I let code go where it needs to go, letting the "true" conditions happen first, and let else handle the "false" conditions.. In the end, I also strive to have a single point of exit instead of having multiple returns sprinkled throughout a method.

                                      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                      -----
                                      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                      -----
                                      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                      D Offline
                                      D Offline
                                      Dr Walt Fair PE
                                      wrote on last edited by
                                      #19

                                      John Simmons / outlaw programmer wrote:

                                      I also strive to have a single point of exit instead of having multiple returns sprinkled throughout a method.

                                      **Boring...**You're taking all the fun out of debugging!!

                                      CQ de W5ALT

                                      Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                                      R 1 Reply Last reply
                                      0
                                      • D Dr Walt Fair PE

                                        John Simmons / outlaw programmer wrote:

                                        I also strive to have a single point of exit instead of having multiple returns sprinkled throughout a method.

                                        **Boring...**You're taking all the fun out of debugging!!

                                        CQ de W5ALT

                                        Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                                        R Offline
                                        R Offline
                                        realJSOP
                                        wrote on last edited by
                                        #20

                                        Yeah, I know. But debugging is exciting enough without adding multiple-exit-points sauce. :)

                                        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                        -----
                                        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                        -----
                                        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                        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