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. goto [modified]

goto [modified]

Scheduled Pinned Locked Moved The Lounge
questioncom
73 Posts 25 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 Rei Miyasaka

    Christian Graus wrote:

    Not sure what you mean by 'making private methods for the sake of avoiding goto', if you have code that needs to be pointed to only sometimes, refactoring it to a new method just makes sense.

    Eh, now that you ask, I can't think of any examples. Maybe you have a point. So what makes it bad if you know not to use it in a bad way?

    C Offline
    C Offline
    Christian Graus
    wrote on last edited by
    #31

    There is no circumstance in which it doesn't create code that's less readable than if you use a method to call, or try/catch. I've simply never looked at code I wrote and thought 'if only I could use goto'.

    Christian Graus - Microsoft MVP - C++ "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

    1 Reply Last reply
    0
    • L leppie

      Christian Graus wrote:

      The closest I would get is to regard goto as another way to handle code that is at least as well handled by try/catch.

      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
      A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll

      xacc.ide
      IronScheme a R5RS-compliant Scheme on the DLR
      The rule of three: "The first time you notice something that might repeat, don't generalize it. The second time the situation occurs, develop in a similar fashion -- possibly even copy/paste -- but don't generalize yet. On the third time, look to generalize the approach."

      C Offline
      C Offline
      Christian Graus
      wrote on last edited by
      #32

      I'm sure your point is obvious to you, but it escapes me

      Christian Graus - Microsoft MVP - C++ "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

      1 Reply Last reply
      0
      • R Rei Miyasaka

        Shog9 wrote:

        No, it's because i don't need it.

        It's not ever necessary, no, but my question is, can it make things more readable sometimes? Is it being unnecessarily demonized?

        Shog9 wrote:

        Actually, i'd argue that a sufficient quantity of properly-chosen (and named...) private methods not only makes the code more readable, but also effectively eliminates most scenarios where internal booleans, long conditionals, or gotos might otherwise be used. And that's a good thing.

        That means several things though: -I have to scroll up and down to jump between methods -I have to choose the locals that I want to use (not so bad with Refractor) -If I ever want to change those locals, I have to change the code in two locations: the call arguments and the method parameters -I have to sit down and think of a name. And I spend a lot of time coming up with good names, because if I don't, it affects my reasoning later on.

        Shog9 wrote:

        or gotos might otherwise be used. And that's a good thing.

        Sure, but why?

        S Offline
        S Offline
        S Senthil Kumar
        wrote on last edited by
        #33

        I find that private methods help me read and understand code better. Compare

        void ProcessResults(Data d)
        {
        if (d.cond1 && (d.cond2 || d.cond3)
        {
        ...
        }
        }

        with

        void ProcessResult(Data d)
        {
        if (IsType1(data)
        {
        ...
        }
        }

        private bool IsType1(data)
        {
        return data.cond1 && (data.cond2 || data.cond3);
        }

        When reading ProcessResult, I don't need to figure what the boolean logic is trying to do (another layer of abstraction, if you will). This keeps the focus on ProcessResult's code flow

        Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

        R 1 Reply Last reply
        0
        • S S Senthil Kumar

          I find that private methods help me read and understand code better. Compare

          void ProcessResults(Data d)
          {
          if (d.cond1 && (d.cond2 || d.cond3)
          {
          ...
          }
          }

          with

          void ProcessResult(Data d)
          {
          if (IsType1(data)
          {
          ...
          }
          }

          private bool IsType1(data)
          {
          return data.cond1 && (data.cond2 || data.cond3);
          }

          When reading ProcessResult, I don't need to figure what the boolean logic is trying to do (another layer of abstraction, if you will). This keeps the focus on ProcessResult's code flow

          Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

          R Offline
          R Offline
          Rei Miyasaka
          wrote on last edited by
          #34

          I don't think I'd ever name a method ProcessResults. Well, maybe I have in the past. If it's an override or interface implementation or something and I have no option but to use that name, and the logic isn't straightforward, I'd just comment it. Especially if it involves any sort of math.

          S 1 Reply Last reply
          0
          • R Rei Miyasaka

            Shog9 wrote:

            No, it's because i don't need it.

            It's not ever necessary, no, but my question is, can it make things more readable sometimes? Is it being unnecessarily demonized?

            Shog9 wrote:

            Actually, i'd argue that a sufficient quantity of properly-chosen (and named...) private methods not only makes the code more readable, but also effectively eliminates most scenarios where internal booleans, long conditionals, or gotos might otherwise be used. And that's a good thing.

            That means several things though: -I have to scroll up and down to jump between methods -I have to choose the locals that I want to use (not so bad with Refractor) -If I ever want to change those locals, I have to change the code in two locations: the call arguments and the method parameters -I have to sit down and think of a name. And I spend a lot of time coming up with good names, because if I don't, it affects my reasoning later on.

            Shog9 wrote:

            or gotos might otherwise be used. And that's a good thing.

            Sure, but why?

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

            reinux wrote:

            It's not ever necessary, no, but my question is, can it make things more readable sometimes? Is it being unnecessarily demonized?

            No. Well, yeah, probably - i mean, why bother to demonize a keyword, even if it is generally misused by people who don't know what they're doing. But i'd say it's use is discouraged and rightly so. Look, goto is primitive, a very simple building-block. Unconditional transfer. Right? But the thing is, you always want conditional transfer. Think about it - you'll always use some sort of conditional to control whether or not the goto is ever reached. This is old stuff, bordering on the je | _ne stuff |_ jmp assembler pattern or similar. It's tedious, hard to read, and error-prone, which is why we've spent decades building wrappers into the languages themselves. The other unconditionals have very strict limits on them - break, continue, return... all transfer control, but in very specific ways. You see a return, you know you're done with the current method. You see a break, you know you're leaving the current loop (or switch...), etc. You read them and, provided you're keeping your methods and loops fairly short, can know immediately what's going to happen. goto is more of a wildcard... you can't read it without wondering what sort of odd thing is happening such that more limited control structures couldn't be used in place. I mean, heck - you can simulate subroutines with longjmp() too, but why would you want to? ;) And yeah, it can make things more readable sometimes. Usually when things are next-to-unreadable already, and your only other hope of avoiding complete disaster is to re-write the whole mess. Which is fine, but not a good reason to start looking for excuses to work them into brand-new code.

            reinux wrote:

            That means several things though: -I have to scroll up and down to jump between methods

            If you want to read or trace through every single line of code, you'll be scrolling and jumping around anyway. If you're just trying to get a clear high-level picture of the logic or to find one particular area, now you'll have a ready index to help you.

            reinux wrote:

            -I have to choose the locals that I want to use

            Well... duh. How is this relevant? Do you normally work off of a big fa

            R 1 Reply Last reply
            0
            • R Rei Miyasaka

              I don't think I'd ever name a method ProcessResults. Well, maybe I have in the past. If it's an override or interface implementation or something and I have no option but to use that name, and the logic isn't straightforward, I'd just comment it. Especially if it involves any sort of math.

              S Offline
              S Offline
              S Senthil Kumar
              wrote on last edited by
              #36

              You are missing the point. I was trying to point out that reading a method is simpler when it is written so that it calls out to other methods for any logic unrelated to it. The method then can be read like pseudocode, with the internals hidden inside other methods.

              Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

              R 1 Reply Last reply
              0
              • R Rei Miyasaka

                Okay, so this isn't 100% a lounge question, but I'm asking this to stir controversy for the sake of entertainment, so I'll post here. Is goto really that bad? I'm beginning to wonder if it's just peer pressure and scariness that's making people avoid it. There are undeniably occasions in which goto enables the most readable code. Making private methods just for the sake of avoiding goto seems more spaghetti to me, as does using more local booleans and if/elses for flagging. If I were a teacher, I might not teach students to use goto, because they'll likely abuse it. But if I was evaluating a student's code and they use goto appropriately, I'd probably give them bonus marks for being bold. So, is it only because you've been taught not to use goto that you don't use it? -- modified at 22:22 Friday 23rd November, 2007 Or... http://xkcd.com/292/[^] By the way, let me restate the question: I know goto isn't necessary, but are there cases in which it's more appropriate?

                M Offline
                M Offline
                MikeMarq
                wrote on last edited by
                #37

                Yes there are good uses for goto. I had never used a goto before the program I am writing now but I have used maybe 8 gotos in about 5000 lines of code and I think they are all good uses for it. The reason I used it is because I have a number of functions that have to make all or nothing evaluations of arrays of objects where for instance if any 2 items in 2 different arrays are the same then the function returns true regardless of anything else. Or the opposite where if anything test false then the answer is false(I'm oversimplifying a bit but you get the idea). In these situations you might know the answer after only the first comparison. I use the gotos to escape the nested loops so I don't do a ton of unnecisary comparisons. I also used it inside an inside loop in a heavily used function to avoid having to reevaluate something. Most of the examples of the never use a goto people are unrealistic examples IMHO. This is alot like the people who claim recursion should never be used, who then trot out some silly example like calculating factorials where a simple loop would work fine.

                1 Reply Last reply
                0
                • R Rei Miyasaka

                  Okay, so this isn't 100% a lounge question, but I'm asking this to stir controversy for the sake of entertainment, so I'll post here. Is goto really that bad? I'm beginning to wonder if it's just peer pressure and scariness that's making people avoid it. There are undeniably occasions in which goto enables the most readable code. Making private methods just for the sake of avoiding goto seems more spaghetti to me, as does using more local booleans and if/elses for flagging. If I were a teacher, I might not teach students to use goto, because they'll likely abuse it. But if I was evaluating a student's code and they use goto appropriately, I'd probably give them bonus marks for being bold. So, is it only because you've been taught not to use goto that you don't use it? -- modified at 22:22 Friday 23rd November, 2007 Or... http://xkcd.com/292/[^] By the way, let me restate the question: I know goto isn't necessary, but are there cases in which it's more appropriate?

                  R Offline
                  R Offline
                  Ray Cassick
                  wrote on last edited by
                  #38

                  Anything used incorrectly is bad. I think the argument about goto is that it simply gives developers an easy-out rather than making them think up better constructs. As with anything there are good and bad ways to use it. Goto just seems to have way more bad ways than good ways... ...and this is coming from a die-hard VBer :)


                  My Blog[^]
                  FFRF[^]


                  1 Reply Last reply
                  0
                  • S Shog9 0

                    reinux wrote:

                    It's not ever necessary, no, but my question is, can it make things more readable sometimes? Is it being unnecessarily demonized?

                    No. Well, yeah, probably - i mean, why bother to demonize a keyword, even if it is generally misused by people who don't know what they're doing. But i'd say it's use is discouraged and rightly so. Look, goto is primitive, a very simple building-block. Unconditional transfer. Right? But the thing is, you always want conditional transfer. Think about it - you'll always use some sort of conditional to control whether or not the goto is ever reached. This is old stuff, bordering on the je | _ne stuff |_ jmp assembler pattern or similar. It's tedious, hard to read, and error-prone, which is why we've spent decades building wrappers into the languages themselves. The other unconditionals have very strict limits on them - break, continue, return... all transfer control, but in very specific ways. You see a return, you know you're done with the current method. You see a break, you know you're leaving the current loop (or switch...), etc. You read them and, provided you're keeping your methods and loops fairly short, can know immediately what's going to happen. goto is more of a wildcard... you can't read it without wondering what sort of odd thing is happening such that more limited control structures couldn't be used in place. I mean, heck - you can simulate subroutines with longjmp() too, but why would you want to? ;) And yeah, it can make things more readable sometimes. Usually when things are next-to-unreadable already, and your only other hope of avoiding complete disaster is to re-write the whole mess. Which is fine, but not a good reason to start looking for excuses to work them into brand-new code.

                    reinux wrote:

                    That means several things though: -I have to scroll up and down to jump between methods

                    If you want to read or trace through every single line of code, you'll be scrolling and jumping around anyway. If you're just trying to get a clear high-level picture of the logic or to find one particular area, now you'll have a ready index to help you.

                    reinux wrote:

                    -I have to choose the locals that I want to use

                    Well... duh. How is this relevant? Do you normally work off of a big fa

                    R Offline
                    R Offline
                    Rei Miyasaka
                    wrote on last edited by
                    #39

                    Shog9 wrote:

                    It's tedious, hard to read, and error-prone, which is why we've spent decades building wrappers into the languages themselves.

                    Yeah, but structured languages aren't exempt from leaky abstraction[^] of code flow. It's been decades since C and we still haven't come up with a good be all end all solution for breaking out of nested switches or loops. We're also still using Win32API a lot, which means we don't always have the luxury of using exception handling. Obviously I'm thankful that I don't have to use goto all the time, but that doesn't mean I'll never want to use it.

                    Shog9 wrote:

                    Which is fine, but not a good reason to start looking for excuses to work them into brand-new code.

                    Never would do that. Which is why I said that if I were a teacher, I wouldn't encourage students to use it, but if someone did use it well, I'd applaud them.

                    Shog9 wrote:

                    If you want to read or trace through every single line of code, you'll be scrolling and jumping around anyway.

                    Exactly, which is why I like to keep that at a minimum. Just because it happens doesn't mean I don't care if it happens more often.

                    Shog9 wrote:

                    If you're just trying to get a clear high-level picture of the logic or to find one particular area, now you'll have a ready index to help you.

                    That's what indentation is for. Heck, I often add scope brackets just to indicate logical blocks of code. I can remember code as mental symbols that mean exactly what they do, rather than having to come up with English names that might potentially have slightly different nuances from what I'm doing. I write my code in a way that you can infer the purpose and execution flow from the shape of the code. Everything executes in a general top-to-bottom order (unless the same code happens twice or more, in which case I'll refractor), and the indentations indicate sub-routines. Which is why I don't like having processing code in the middle of search code like this[

                    S 1 Reply Last reply
                    0
                    • R Rei Miyasaka

                      Okay, so this isn't 100% a lounge question, but I'm asking this to stir controversy for the sake of entertainment, so I'll post here. Is goto really that bad? I'm beginning to wonder if it's just peer pressure and scariness that's making people avoid it. There are undeniably occasions in which goto enables the most readable code. Making private methods just for the sake of avoiding goto seems more spaghetti to me, as does using more local booleans and if/elses for flagging. If I were a teacher, I might not teach students to use goto, because they'll likely abuse it. But if I was evaluating a student's code and they use goto appropriately, I'd probably give them bonus marks for being bold. So, is it only because you've been taught not to use goto that you don't use it? -- modified at 22:22 Friday 23rd November, 2007 Or... http://xkcd.com/292/[^] By the way, let me restate the question: I know goto isn't necessary, but are there cases in which it's more appropriate?

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

                      Yes, the goto is really that bad. I've found that once you tolerate any use of goto, some developers will abuse it severely. Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms. I have learned this by experience. I have maintained a lot of code chock full of gotos, but I have chosen to use one precisely once in nineteen years of C/C++ programming. (When doing assembly programming, I use the equivalent, but you really have no choice. However, even there, if I'm jmp'ing more than a page of code, I'd take a very close look at my algorithm.) Personally, I would fail any student using a goto (I won't hire anyone who uses them more than extremely sparingly.) Later, if this person encounters a situation where a goto appears to be the best solution, it will make them think long and hard and examine their code carefully before making a deliberate decision. And they'd better document why. (BTW, I rarely have problems with memory leaks in C/C++. The developers I've dealt with that use gotos tend to have memory leaks. It don't think it's coincidental.)

                      Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                      R T 2 Replies Last reply
                      0
                      • S S Senthil Kumar

                        You are missing the point. I was trying to point out that reading a method is simpler when it is written so that it calls out to other methods for any logic unrelated to it. The method then can be read like pseudocode, with the internals hidden inside other methods.

                        Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                        R Offline
                        R Offline
                        Rei Miyasaka
                        wrote on last edited by
                        #41

                        That's what indentation is for. Heck, I often add scope brackets just to indicate logical blocks of code. I can remember code as mental symbols that mean exactly what they do, rather than having to come up with English names that might potentially have slightly different nuances from what I'm doing. I write my code in a way that you can infer the purpose and execution flow from the shape of the code. Everything executes in a general top-to-bottom order (unless the same code happens twice or more, in which case I'll refractor), and the indentations indicate sub-routines. Which is why I don't like having processing code in the middle of search code like this[^]. Makes it a lot easier to remember code too, because you get a one-to-one association between the visual shape of your code and its function.

                        I suppose refractoring a lot gives you the pseudocode-ish-ness advantage, but it's a pain when you're debugging, and once you forget what all those esoteric function names mean, you're going to end up having to peek inside anyway. So in a sense both ways of thinking have their advantages at different stages of development. The question would then be, which is simpler in the big picture? And honestly, I don't know, but you could argue for both.

                        1 Reply Last reply
                        0
                        • J Joe Woodbury

                          Yes, the goto is really that bad. I've found that once you tolerate any use of goto, some developers will abuse it severely. Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms. I have learned this by experience. I have maintained a lot of code chock full of gotos, but I have chosen to use one precisely once in nineteen years of C/C++ programming. (When doing assembly programming, I use the equivalent, but you really have no choice. However, even there, if I'm jmp'ing more than a page of code, I'd take a very close look at my algorithm.) Personally, I would fail any student using a goto (I won't hire anyone who uses them more than extremely sparingly.) Later, if this person encounters a situation where a goto appears to be the best solution, it will make them think long and hard and examine their code carefully before making a deliberate decision. And they'd better document why. (BTW, I rarely have problems with memory leaks in C/C++. The developers I've dealt with that use gotos tend to have memory leaks. It don't think it's coincidental.)

                          Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                          R Offline
                          R Offline
                          Rei Miyasaka
                          wrote on last edited by
                          #42

                          Joe Woodbury wrote:

                          I've found that once you tolerate any use of goto, some developers will abuse it severely.

                          That might be a good point as an employer. What if you're the one using goto, and you trust yourself with it?

                          Joe Woodbury wrote:

                          Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms.

                          Yeah, all these things can happen if you misuse it, but unreadable code and poor algorithms happen for a lot of reasons. What I'm suggesting is that, perhaps, the lack of goto can also result in such.

                          Joe Woodbury wrote:

                          (BTW, I rarely have problems with memory leaks in C/C++. The developers I've dealt with that use gotos tend to have memory leaks. It don't think it's coincidental.)

                          Yeah, I'd say. If their code is "chock full" of gotos, there's obviously a problem. Also I don't remember if C/C++ lets you goto out of a function (I never used it back then), but if it does, and people do that, well, there's your memory leak potential. I wouldn't goto over more than a few lines of code myself either.

                          1 Reply Last reply
                          0
                          • R Rei Miyasaka

                            Shog9 wrote:

                            It's tedious, hard to read, and error-prone, which is why we've spent decades building wrappers into the languages themselves.

                            Yeah, but structured languages aren't exempt from leaky abstraction[^] of code flow. It's been decades since C and we still haven't come up with a good be all end all solution for breaking out of nested switches or loops. We're also still using Win32API a lot, which means we don't always have the luxury of using exception handling. Obviously I'm thankful that I don't have to use goto all the time, but that doesn't mean I'll never want to use it.

                            Shog9 wrote:

                            Which is fine, but not a good reason to start looking for excuses to work them into brand-new code.

                            Never would do that. Which is why I said that if I were a teacher, I wouldn't encourage students to use it, but if someone did use it well, I'd applaud them.

                            Shog9 wrote:

                            If you want to read or trace through every single line of code, you'll be scrolling and jumping around anyway.

                            Exactly, which is why I like to keep that at a minimum. Just because it happens doesn't mean I don't care if it happens more often.

                            Shog9 wrote:

                            If you're just trying to get a clear high-level picture of the logic or to find one particular area, now you'll have a ready index to help you.

                            That's what indentation is for. Heck, I often add scope brackets just to indicate logical blocks of code. I can remember code as mental symbols that mean exactly what they do, rather than having to come up with English names that might potentially have slightly different nuances from what I'm doing. I write my code in a way that you can infer the purpose and execution flow from the shape of the code. Everything executes in a general top-to-bottom order (unless the same code happens twice or more, in which case I'll refractor), and the indentations indicate sub-routines. Which is why I don't like having processing code in the middle of search code like this[

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

                            reinux wrote:

                            We're also still using Win32API a lot, which means we don't always have the luxury of using exception handling.

                            Right, but that's generally pretty low-level stuff. Wrap it with something that makes sense for your program and be done with it.

                            reinux wrote:

                            Obviously I'm thankful that I don't have to use goto all the time, but that doesn't mean I'll never want to use it.

                            Of course. I'm not saying "anyone who ever uses goto is a bad person". But it's probably a good red flag, a reason to step back and think about whether or not what you're doing really makes good sense. BTW - someone earlier mentioned RAII as a good technique for avoiding the error-handling use of goto - if you wrap your low-level API calls in RAII-friendly classes, you can toss in return code / GetLastError()-to-exception mapping as well, and just be done with it. We have trivial little wrappers floating around for most non-trivial Win32 APIs; read MSDN, write a few tests to verify that the docs are correct, and then wrap it up so it can't be misused accidentally.

                            reinux wrote:

                            That's what indentation is for.

                            I hate seeing indentation deeper than maybe three levels. Personal preference then. :-O

                            reinux wrote:

                            Makes it a lot easier to remember code too, because you get a one-to-one association between the visual shape of your code and its function.

                            Absolutely true. Unfortunately, it doesn't scale. When you have to scroll through 200 lines of code to see the entire "shape", it's much harder to recognize and factor out duplicate code. Then you fix a bug in one place and the shapes no longer match up, or worse, they do but the code doesn't - and you end up with new maintainers pulling the wrong chunk of code and propagating the bug rather than the fix.

                            reinux wrote:

                            Say for instance I have a local XmlDocument that I'm going to be using throughout the entire method. I have to keep this in mind when I refractor bits and pieces of the method.

                            Well, to me that's another argument in favor of just breaking it up into routines that each do just one, self-contained operation on the document. Now you're passing the document in as an argument to each, but it means something different to each routine. Best yet, when you're r

                            R 1 Reply Last reply
                            0
                            • S Shog9 0

                              reinux wrote:

                              We're also still using Win32API a lot, which means we don't always have the luxury of using exception handling.

                              Right, but that's generally pretty low-level stuff. Wrap it with something that makes sense for your program and be done with it.

                              reinux wrote:

                              Obviously I'm thankful that I don't have to use goto all the time, but that doesn't mean I'll never want to use it.

                              Of course. I'm not saying "anyone who ever uses goto is a bad person". But it's probably a good red flag, a reason to step back and think about whether or not what you're doing really makes good sense. BTW - someone earlier mentioned RAII as a good technique for avoiding the error-handling use of goto - if you wrap your low-level API calls in RAII-friendly classes, you can toss in return code / GetLastError()-to-exception mapping as well, and just be done with it. We have trivial little wrappers floating around for most non-trivial Win32 APIs; read MSDN, write a few tests to verify that the docs are correct, and then wrap it up so it can't be misused accidentally.

                              reinux wrote:

                              That's what indentation is for.

                              I hate seeing indentation deeper than maybe three levels. Personal preference then. :-O

                              reinux wrote:

                              Makes it a lot easier to remember code too, because you get a one-to-one association between the visual shape of your code and its function.

                              Absolutely true. Unfortunately, it doesn't scale. When you have to scroll through 200 lines of code to see the entire "shape", it's much harder to recognize and factor out duplicate code. Then you fix a bug in one place and the shapes no longer match up, or worse, they do but the code doesn't - and you end up with new maintainers pulling the wrong chunk of code and propagating the bug rather than the fix.

                              reinux wrote:

                              Say for instance I have a local XmlDocument that I'm going to be using throughout the entire method. I have to keep this in mind when I refractor bits and pieces of the method.

                              Well, to me that's another argument in favor of just breaking it up into routines that each do just one, self-contained operation on the document. Now you're passing the document in as an argument to each, but it means something different to each routine. Best yet, when you're r

                              R Offline
                              R Offline
                              Rei Miyasaka
                              wrote on last edited by
                              #44

                              Shog9 wrote:

                              Right, but that's generally pretty low-level stuff.

                              If that were true, most WinForms apps would be portable to Mono. Alas, the majority aren't. It's so severe in fact that .NET has earned its notorious reputation of lacking portability even despite a full open-source reimplementation.

                              Shog9 wrote:

                              We have trivial little wrappers floating around for most non-trivial Win32 APIs; read MSDN, write a few tests to verify that the docs are correct, and then wrap it up so it can't be misused accidentally.

                              That's not a bad idea. But it doesn't have too much to do with whether or not you hate gotos; it's just how you'd avoid using a goto. Which, again, do you really need to?

                              Shog9 wrote:

                              Absolutely true. Unfortunately, it doesn't scale. When you have to scroll through 200 lines of code to see the entire "shape", it's much harder to recognize and factor out duplicate code. Then you fix a bug in one place and the shapes no longer match up, or worse, they do but the code doesn't - and you end up with new maintainers pulling the wrong chunk of code and propagating the bug rather than the fix.

                              Again, I usually comment code if its function is non-trivial. Which means rather than giving a piece of code a "name", I give it a full-sentence description. Though I agree, at around 200 lines, I'd start thinking about pulling pieces out. Just not as early as the 25 lines that someone earlier suggested.

                              Shog9 wrote:

                              Well, to me that's another argument in favor of just breaking it up into routines that each do just one, self-contained operation on the document. Now you're passing the document in as an argument to each, but it means something different to each routine.

                              I'm not sure how in this case refractoring is an advantage.

                              Shog9 wrote:

                              Best yet, when you're reading the routines that don't use the document, you don't have it hanging around as a possible point of confusion.

                              That's a good point.

                              Shog9 wrote:

                              if i can't summarize it in a short sentence (method name), then i probably need to re-think how i've written the code in the first place.

                              It wouldn't be so much the grammar of the method name that I'd worry about forgetting (in PowerShell for insta

                              S 1 Reply Last reply
                              0
                              • A Anthony Mushrow

                                I was taught that its OK to create a method, how ever small it may be, if even for only 1 line of code (although that would be completely pointless wouldn't it?) as it makes the code easier to update and maintain at a later date. I was also taught, and have heard, and imagined, that goto can create a really big mess, it it would be wise to avoid it. As it is, i've not come across the need for a goto.

                                My current favourite word is: PIE! Good ol' pie, it's been a while.

                                P Offline
                                P Offline
                                Pawel Krakowiak
                                wrote on last edited by
                                #45

                                The Undefeated wrote:

                                I was taught that its OK to create a method, how ever small it may be, if even for only 1 line of code (although that would be completely pointless wouldn't it?)

                                It wouldn't be pointless if that method was called in several places.

                                Kind regards, Pawel Krakowiak Miraculum Software[^]

                                1 Reply Last reply
                                0
                                • J Joe Woodbury

                                  Yes, the goto is really that bad. I've found that once you tolerate any use of goto, some developers will abuse it severely. Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms. I have learned this by experience. I have maintained a lot of code chock full of gotos, but I have chosen to use one precisely once in nineteen years of C/C++ programming. (When doing assembly programming, I use the equivalent, but you really have no choice. However, even there, if I'm jmp'ing more than a page of code, I'd take a very close look at my algorithm.) Personally, I would fail any student using a goto (I won't hire anyone who uses them more than extremely sparingly.) Later, if this person encounters a situation where a goto appears to be the best solution, it will make them think long and hard and examine their code carefully before making a deliberate decision. And they'd better document why. (BTW, I rarely have problems with memory leaks in C/C++. The developers I've dealt with that use gotos tend to have memory leaks. It don't think it's coincidental.)

                                  Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                                  T Offline
                                  T Offline
                                  Tony Wesley
                                  wrote on last edited by
                                  #46

                                  Joe Woodbury wrote:

                                  I've found that once you tolerate any use of goto, some developers will abuse it severely. Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms. I have learned this by experience. I have maintained a lot of code chock full of gotos, but I have chosen to use one precisely once in nineteen years of C/C++ programming.[...]

                                  We have different experiences. I've seen very few goto's as a professional programmer ... wait, except for those FORTRAN days. Actually, that's going to tie into the point I'm about to make. Different languages have different program control mechanisms. I used to program in a language called Clarion. One of the constructs I likes in that language was the ability to write loop 1 times. No index variable. I would wrap it around a series of if/then/else if and break to exit early. In C/C++, I accomplish the same with this

                                  while (true)   // loop 1 time, exit at bottom
                                  {
                                      if (set (ifrFragment))
                                      {
                                          result = true;
                                          ifrTerm = ifrFragment;
                                          break;            
                                      }
                                      if (errorCode)
                                          break;
                                  
                                      if (keyword (TokenSubtype::Not) && term (ifrFragment))
                                      {
                                          result = true;
                                          ifrTerm = TokenSubtype::Not.asString() + " " + ifrFragment;
                                          break;
                                      }
                                      if (errorCode)
                                          break;
                                    // more lines snipped
                                     break;
                                  }
                                  

                                  Robert Surtees writes We used to do it to piss off the "never use goto" zealots years ago when forbidden to use 'goto xit' for handling error conditions. And he's right. I could have done the same like this, with one few level of indentation:

                                  if (set (ifrFragment))
                                  {
                                      result = true;
                                      ifrTerm = ifrFragment;
                                      goto exit\_;            
                                  }
                                  if (errorCode)
                                      goto exit\_;
                                  
                                  if (keyword (TokenSubtype::Not) && term (ifrFragment))
                                  {
                                      result = true;
                                      ifrTerm = TokenSubtype::Not.asString() + " " + ifrFragment;
                                      goto exit\_;
                                  }
                                  if (errorCode)
                                      goto exit\_;
                                  

                                  // more lines snipped
                                  exit_:

                                  So in the first example, I'm doing goto's -- without using them explicitly. Anyway, to get to my point: since different language have different control

                                  J 1 Reply Last reply
                                  0
                                  • R Rei Miyasaka

                                    Shog9 wrote:

                                    Right, but that's generally pretty low-level stuff.

                                    If that were true, most WinForms apps would be portable to Mono. Alas, the majority aren't. It's so severe in fact that .NET has earned its notorious reputation of lacking portability even despite a full open-source reimplementation.

                                    Shog9 wrote:

                                    We have trivial little wrappers floating around for most non-trivial Win32 APIs; read MSDN, write a few tests to verify that the docs are correct, and then wrap it up so it can't be misused accidentally.

                                    That's not a bad idea. But it doesn't have too much to do with whether or not you hate gotos; it's just how you'd avoid using a goto. Which, again, do you really need to?

                                    Shog9 wrote:

                                    Absolutely true. Unfortunately, it doesn't scale. When you have to scroll through 200 lines of code to see the entire "shape", it's much harder to recognize and factor out duplicate code. Then you fix a bug in one place and the shapes no longer match up, or worse, they do but the code doesn't - and you end up with new maintainers pulling the wrong chunk of code and propagating the bug rather than the fix.

                                    Again, I usually comment code if its function is non-trivial. Which means rather than giving a piece of code a "name", I give it a full-sentence description. Though I agree, at around 200 lines, I'd start thinking about pulling pieces out. Just not as early as the 25 lines that someone earlier suggested.

                                    Shog9 wrote:

                                    Well, to me that's another argument in favor of just breaking it up into routines that each do just one, self-contained operation on the document. Now you're passing the document in as an argument to each, but it means something different to each routine.

                                    I'm not sure how in this case refractoring is an advantage.

                                    Shog9 wrote:

                                    Best yet, when you're reading the routines that don't use the document, you don't have it hanging around as a possible point of confusion.

                                    That's a good point.

                                    Shog9 wrote:

                                    if i can't summarize it in a short sentence (method name), then i probably need to re-think how i've written the code in the first place.

                                    It wouldn't be so much the grammar of the method name that I'd worry about forgetting (in PowerShell for insta

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

                                    reinux wrote:

                                    But it doesn't have too much to do with whether or not you hate gotos; it's just how you'd avoid using a goto.

                                    If i'd solved the problem (of releasing resources on failure) using goto, the code would still have worked, yes. But now i'm letting the archaic design of the Win32 API pollute the rest of my code - something i do not wish to see at all. So really, what's the point? Perhaps i can save a small amount of time up-front by using goto, but at the cost of harder-to-read, error-prone code. It's not just how - it's also a good part of why.

                                    reinux wrote:

                                    Generally speaking, you could use a knife maliciously in a myriad of ways, but you can use one benevolently only maybe to cut veggies and open envelopes.

                                    But you probably wouldn't use a letter-opener to slice veggies. In fact, i don't even keep mine in my kitchen. Sure, i could probably use it in a pinch, but i'd rather just avoid that scenario altogether. ;)

                                    ----

                                    ...the wind blows over it and it is gone, and its place remembers it no more...

                                    R 1 Reply Last reply
                                    0
                                    • S Shog9 0

                                      reinux wrote:

                                      But it doesn't have too much to do with whether or not you hate gotos; it's just how you'd avoid using a goto.

                                      If i'd solved the problem (of releasing resources on failure) using goto, the code would still have worked, yes. But now i'm letting the archaic design of the Win32 API pollute the rest of my code - something i do not wish to see at all. So really, what's the point? Perhaps i can save a small amount of time up-front by using goto, but at the cost of harder-to-read, error-prone code. It's not just how - it's also a good part of why.

                                      reinux wrote:

                                      Generally speaking, you could use a knife maliciously in a myriad of ways, but you can use one benevolently only maybe to cut veggies and open envelopes.

                                      But you probably wouldn't use a letter-opener to slice veggies. In fact, i don't even keep mine in my kitchen. Sure, i could probably use it in a pinch, but i'd rather just avoid that scenario altogether. ;)

                                      ----

                                      ...the wind blows over it and it is gone, and its place remembers it no more...

                                      R Offline
                                      R Offline
                                      Rei Miyasaka
                                      wrote on last edited by
                                      #48

                                      Shog9 wrote:

                                      If i'd solved the problem (of releasing resources on failure) using goto, the code would still have worked, yes. But now i'm letting the archaic design of the Win32 API pollute the rest of my code - something i do not wish to see at all. So really, what's the point? Perhaps i can save a small amount of time up-front by using goto, but at the cost of harder-to-read, error-prone code. It's not just how - it's also a good part of why.

                                      Well, if you want to write a full-blown wrapper around some Win32 functionality, that's a whole 'nother story.

                                      Shog9 wrote:

                                      But you probably wouldn't use a letter-opener to slice veggies. In fact, i don't even keep mine in my kitchen. Sure, i could probably use it in a pinch, but i'd rather just avoid that scenario altogether.

                                      I meant to compare a knife with a goto, but okay. Anyway, my point is that in agreement with what Ray said, there's a lot of bad ways to use it. But there are probably good ways too.

                                      1 Reply Last reply
                                      0
                                      • T Tony Wesley

                                        Joe Woodbury wrote:

                                        I've found that once you tolerate any use of goto, some developers will abuse it severely. Not only does it create difficult to understand code, it causes scope problems and, worse of all, results in poor algorithms. I have learned this by experience. I have maintained a lot of code chock full of gotos, but I have chosen to use one precisely once in nineteen years of C/C++ programming.[...]

                                        We have different experiences. I've seen very few goto's as a professional programmer ... wait, except for those FORTRAN days. Actually, that's going to tie into the point I'm about to make. Different languages have different program control mechanisms. I used to program in a language called Clarion. One of the constructs I likes in that language was the ability to write loop 1 times. No index variable. I would wrap it around a series of if/then/else if and break to exit early. In C/C++, I accomplish the same with this

                                        while (true)   // loop 1 time, exit at bottom
                                        {
                                            if (set (ifrFragment))
                                            {
                                                result = true;
                                                ifrTerm = ifrFragment;
                                                break;            
                                            }
                                            if (errorCode)
                                                break;
                                        
                                            if (keyword (TokenSubtype::Not) && term (ifrFragment))
                                            {
                                                result = true;
                                                ifrTerm = TokenSubtype::Not.asString() + " " + ifrFragment;
                                                break;
                                            }
                                            if (errorCode)
                                                break;
                                          // more lines snipped
                                           break;
                                        }
                                        

                                        Robert Surtees writes We used to do it to piss off the "never use goto" zealots years ago when forbidden to use 'goto xit' for handling error conditions. And he's right. I could have done the same like this, with one few level of indentation:

                                        if (set (ifrFragment))
                                        {
                                            result = true;
                                            ifrTerm = ifrFragment;
                                            goto exit\_;            
                                        }
                                        if (errorCode)
                                            goto exit\_;
                                        
                                        if (keyword (TokenSubtype::Not) && term (ifrFragment))
                                        {
                                            result = true;
                                            ifrTerm = TokenSubtype::Not.asString() + " " + ifrFragment;
                                            goto exit\_;
                                        }
                                        if (errorCode)
                                            goto exit\_;
                                        

                                        // more lines snipped
                                        exit_:

                                        So in the first example, I'm doing goto's -- without using them explicitly. Anyway, to get to my point: since different language have different control

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

                                        A few years back, I maintained a project which used the "exit_:" construct quite a bit. Unfortunately, many had morphed into something like following (I included their abbreviations-which-make-no-sense to enhance the effect): g3: close(hF1); if (i == 5) goto e1; e2: free pLS; e1: return; (With 'i', of course, being the counter from some loop and having some meaning other than array index.:))

                                        Anyone who thinks he has a better idea of what's good for people than people do is a swine. - P.J. O'Rourke

                                        1 Reply Last reply
                                        0
                                        • R Rei Miyasaka

                                          Ah, but one could argue that exceptions should only be used for errors[^].

                                          Do not use exceptions for normal flow of control. Except for system failures, there should generally be a way to write code that avoids exceptions being thrown.

                                          Error Raising and Handling Guidelines[^]

                                          Do not use exceptions for normal or expected errors, or for normal flow of control.

                                          M Offline
                                          M Offline
                                          Mycroft Holmes
                                          wrote on last edited by
                                          #50

                                          gotto agree with the exception you take to exceptions. A developer should NEVER rely on an error, this includes SQL errors from a stored procs. Coding by error is BAD - I recently offerred to sack a junior who wished to code in this method. Still promoting goto as a viable paradign should get you burnt at the stake as well, there are so many screw ups that have been attributed to badly formed goto!

                                          Quote from Great Outdoors: its a confident traveller who farts in India

                                          R 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