Results 1 to 29 of 29

Thread: What's wrong with GoTo

  1. #1

    Thread Starter
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    What's wrong with GoTo

    I've read many times now that "GoTo is bad, outdated, wrong, hazardous, nasty, and should be avoided at all costs", but just can't see what's so wrong with it. Here's a small bit of code I wrote recently, and I don't see what better way than GoTo is there.

    VB Code:
    1. Public Function ReadLIGH(ByVal FileHandle As Integer, ByRef NextRecordType As String) As ES_LIGH
    2.  
    3. With ReadLIGH
    4.     Get FileHandle, , .Size
    5.     Get FileHandle, , .UnknownHeader1
    6.     Get FileHandle, , .Flag
    7.     Get FileHandle, , NextRecordType
    8. ReadNext:
    9.     Select Case NextRecordType
    10.     Case "NAME"
    11.         Get FileHandle, , .NAMESize
    12.         .NAMEValue = Space$(.NAMESize - 1)
    13.         Get FileHandle, , .NAMEValue
    14.         Seek FileHandle, Seek(FileHandle) + 1
    15.         Get FileHandle, , NextRecordType
    16.         GoTo ReadNext
    17.     Case "MODL"
    18.         Get FileHandle, , .MODLSize
    19.         .MODLValue = Space$(.MODLSize - 1)
    20.         Get FileHandle, , .MODLValue
    21.         Seek FileHandle, Seek(FileHandle) + 1
    22.         Get FileHandle, , NextRecordType
    23.         GoTo ReadNext
    24.     Case "FNAM"
    25.         Get FileHandle, , .FNAMSize
    26.         .FNAMValue = Space$(.FNAMSize - 1)
    27.         Get FileHandle, , .FNAMValue
    28.         Seek FileHandle, Seek(FileHandle) + 1
    29.         Get FileHandle, , NextRecordType
    30.         GoTo ReadNext
    31.     Case "ITEX"
    32.         Get FileHandle, , .ITEXSize
    33.         .ITEXValue = Space$(.ITEXSize - 1)
    34.         Get FileHandle, , .ITEXValue
    35.         Seek FileHandle, Seek(FileHandle) + 1
    36.         Get FileHandle, , NextRecordType
    37.         GoTo ReadNext
    38.     Case "SCRI"
    39.         Get FileHandle, , .SCRISize
    40.         .SCRIValue = Space$(.SCRISize - 1)
    41.         Get FileHandle, , .SCRIValue
    42.         Seek FileHandle, Seek(FileHandle) + 1
    43.         Get FileHandle, , NextRecordType
    44.         GoTo ReadNext
    45.     Case "SNAM"
    46.         Get FileHandle, , .SNAMSize
    47.         .SNAMValue = Space$(.SNAMSize - 1)
    48.         Get FileHandle, , .SNAMValue
    49.         Seek FileHandle, Seek(FileHandle) + 1
    50.         Get FileHandle, , NextRecordType
    51.         GoTo ReadNext
    52.     Case "LHDT"
    53.         Get FileHandle, , .LHDTSize
    54.         Get FileHandle, , .LHDTWeight
    55.         Get FileHandle, , .LHDTValue
    56.         Get FileHandle, , .LHDTTime
    57.         Get FileHandle, , .LHDTRadius
    58.         Get FileHandle, , .LHDTRed
    59.         Get FileHandle, , .LHDTGreen
    60.         Get FileHandle, , .LHDTBlue
    61.         Seek FileHandle, Seek(FileHandle) + 1
    62.         Get FileHandle, , .LHDTFlags
    63.         Get FileHandle, , NextRecordType
    64.         GoTo ReadNext
    65.     Case "DELE"
    66.         'Record Deleted. Skip the data.
    67.         Seek FileHandle, Seek(FileHandle) + 8
    68.         Get FileHandle, , NextRecordType
    69.         GoTo ReadNext
    70.     End Select
    71. End With
    72.  
    73. End Function

  2. #2
    Hyperactive Member
    Join Date
    Jun 2004
    Posts
    468

    Re: What's wrong with GoTo

    To show how I might do it, I've removed the GoTos and added the lines shown in red:
    VB Code:
    1. Public Function ReadLIGH(ByVal FileHandle As Integer, ByRef NextRecordType As String) As ES_LIGH
    2.  
    3. With ReadLIGH
    4.   Get FileHandle, , .Size
    5.   Get FileHandle, , .UnknownHeader1
    6.   Get FileHandle, , .Flag
    7.   Get FileHandle, , NextRecordType
    8.  
    9.   [COLOR=Red]Do[/COLOR]
    10.     Select Case NextRecordType
    11.     Case "NAME"
    12.         Get FileHandle, , .NAMESize
    13.         .NAMEValue = Space$(.NAMESize - 1)
    14.         Get FileHandle, , .NAMEValue
    15.         Seek FileHandle, Seek(FileHandle) + 1
    16.         Get FileHandle, , NextRecordType
    17.     Case "MODL"
    18.         Get FileHandle, , .MODLSize
    19.         .MODLValue = Space$(.MODLSize - 1)
    20.         Get FileHandle, , .MODLValue
    21.         Seek FileHandle, Seek(FileHandle) + 1
    22.         Get FileHandle, , NextRecordType
    23.     Case "FNAM"
    24.         Get FileHandle, , .FNAMSize
    25.         .FNAMValue = Space$(.FNAMSize - 1)
    26.         Get FileHandle, , .FNAMValue
    27.         Seek FileHandle, Seek(FileHandle) + 1
    28.         Get FileHandle, , NextRecordType
    29.     Case "ITEX"
    30.         Get FileHandle, , .ITEXSize
    31.         .ITEXValue = Space$(.ITEXSize - 1)
    32.         Get FileHandle, , .ITEXValue
    33.         Seek FileHandle, Seek(FileHandle) + 1
    34.         Get FileHandle, , NextRecordType
    35.     Case "SCRI"
    36.         Get FileHandle, , .SCRISize
    37.         .SCRIValue = Space$(.SCRISize - 1)
    38.         Get FileHandle, , .SCRIValue
    39.         Seek FileHandle, Seek(FileHandle) + 1
    40.         Get FileHandle, , NextRecordType
    41.     Case "SNAM"
    42.         Get FileHandle, , .SNAMSize
    43.         .SNAMValue = Space$(.SNAMSize - 1)
    44.         Get FileHandle, , .SNAMValue
    45.         Seek FileHandle, Seek(FileHandle) + 1
    46.         Get FileHandle, , NextRecordType
    47.     Case "LHDT"
    48.         Get FileHandle, , .LHDTSize
    49.         Get FileHandle, , .LHDTWeight
    50.         Get FileHandle, , .LHDTValue
    51.         Get FileHandle, , .LHDTTime
    52.         Get FileHandle, , .LHDTRadius
    53.         Get FileHandle, , .LHDTRed
    54.         Get FileHandle, , .LHDTGreen
    55.         Get FileHandle, , .LHDTBlue
    56.         Seek FileHandle, Seek(FileHandle) + 1
    57.         Get FileHandle, , .LHDTFlags
    58.         Get FileHandle, , NextRecordType
    59.     Case "DELE"
    60.         'Record Deleted. Skip the data.
    61.         Seek FileHandle, Seek(FileHandle) + 8
    62.         Get FileHandle, , NextRecordType
    63.     [COLOR=Red]Case Else[/COLOR]
    64.         [COLOR=Red]Exit Do[/COLOR]
    65.     End Select
    66.   [COLOR=Red]Loop[/COLOR]
    67. End With
    68.  
    69. End Function

  3. #3

    Thread Starter
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    Re: What's wrong with GoTo

    Well, that's just another way. I was asking why any other way is better.

  4. #4

  5. #5
    Lively Member
    Join Date
    Dec 2001
    Location
    South Africa
    Posts
    88

    Thumbs up Re: What's wrong with GoTo

    Goto is a useless piece of code. You can do without it as all.

    The case statement does not execute all the code, only the right case.

    Use goto statement when you code error handling only. eg

    VB Code:
    1. Private Sub HandleError()
    2. On Error GoTo Check:
    3.  
    4. 'Code with no errors here
    5.  
    6.  
    7.  
    8. Check:
    9. Select Case Err.Number
    10. Case Is = 12323333
    11. 'code here
    12.  
    13. Case Is = -345599
    14. 'Code here
    15.  
    16. Case Else
    17. 'Code here for all other erros
    18. MsgBox Err.Description & Err.Number, vbOkOnly, "Error"
    19.  
    20. End Select
    21.  
    22. End Sub

    I hope this will help you.

    Wizard
    SA

  6. #6

  7. #7

    Thread Starter
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    Re: What's wrong with GoTo

    The registration at that site doesn't seem to be too fast... Waiting for the confirmation EMail for 10 minutes now - not that much, but still unnatural. Anyway, indeed I do understand that I can perform most tasks without it, but the exact problems that could be produced from using GoTo are still not showing anywhere on the horizon...

  8. #8
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: What's wrong with GoTo

    This is a little bit of a "religious" topic. In the early days of BASIC, Goto was the only way you could do certain things, but it often led to the tangled code people refer to as "Spaghetti" code. You know a plate of tangles noodles, finding the end of one noodle means you have to trace through a bunch of other ones.

    With the advent of modern BASIC, there is much less need for Goto so if you avoid using it you can help insure your code is easier to read and debug. That being said, there is no reason not to use goto if it makes your code simpler as in the following example.
    VB Code:
    1. While Not Finished
    2.     For i = 1 To 100
    3.         If SomethingHappened(i) Then GoTo ExitAllLoops
    4.         DoOtherStuff
    5.     Next i
    6.     Finished = CheckStatus
    7.  Wend
    8.  MaybeDoOtherStuff
    9. ExitAllLoops:
    There are ways to do the same thing without Goto, but not as simply.
    IMHO, feel free to use Goto, just don't get carried away with it.
    ...

  9. #9
    Frenzied Member pnish's Avatar
    Join Date
    Aug 2002
    Location
    Tassie, Oz
    Posts
    1,918

    Re: What's wrong with GoTo

    The Goto debate is one of those issues where everybody has an opinion. I would think the greater majority would say Goto is BAD, but then you ask them 'why?', they say, 'um err, well I read somewhere that you shouldn't use it'.

    I also think the use of Goto (other than On Error Goto), is unnecessary. It can make code difficult to read (and therefore debug) by interrupting the logical top, down flow of a procedure.

    Most VB apps, being event-driven, can be challenging to debug due to the fact that you can never really predict what the user is going to do. The use of Goto only makes it worse.

    As I said, everyone's got an opinion. That was mine. Cheers.
    Pete

    No trees were harmed in the making of this post, however a large number of electrons were greatly inconvenienced.

  10. #10
    Lively Member
    Join Date
    Dec 2001
    Location
    South Africa
    Posts
    88

    Re: What's wrong with GoTo

    Sorry, my mistake.

    Thanks

    Wizard

  11. #11

  12. #12
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,632

    Re: What's wrong with GoTo

    Code:
    Do While Not Finished
        For i = 1 To 100
            If SomethingHappened(i) Then Do
            DoOtherStuff
        Next i
        Finished = CheckStatus
    Loop
    If Finished Then
        MaybeDoOtherStuff
    End If
    Why use something that has the potential to breed extremely complicated code, which is hard to debug, when there are alternative methods, which provide much easier and neater code?

    Gotos and Gosubs were used because there were no such things as subs or functions.
    So in Basic, you would have had (Amstrad CPC 6218):
    Code:
    10 Print "Woof"
    20 Gosub 80
    30 Print "Growl"
    40 Gosub 80
    50 Print "Moose"
    60 Gosub 80
    70 End
    80 For x = 1 To 10
    90 Print x + 2
    100 Next
    110 Return
    Only line I am not sure about is 70. Hmmmm...anyways. Gosubs are required here. It creates a kind of function.
    In VB6 this would be like doing:
    Code:
    Private Sub Form_Load()
       Debug.Print "Woof"
       DoStuff
       Debug.Print "Growl"
       DoStuff
       Debug.Print "Moose"
       DoStuff
       Unload Me
    End Sub
    
    Private Sub DoStuff()
    Dim x As Long
       For x = 1 to 10
          Debug.Print CStr(x+2)
       Next x
    End Sub
    One question. You do use Option Explicit at the top of your code right?

    Woka

  13. #13
    Frenzied Member
    Join Date
    Aug 2000
    Location
    O!
    Posts
    1,177

    Re: What's wrong with GoTo

    Quote Originally Posted by moeur
    there is no reason not to use goto if it makes your code simpler as in the following example.
    VB Code:
    1. While Not Finished
    2.     For i = 1 To 100
    3.         If SomethingHappened(i) Then GoTo ExitAllLoops
    4.         DoOtherStuff
    5.     Next i
    6.     Finished = CheckStatus
    7.  Wend
    8.  MaybeDoOtherStuff
    9. ExitAllLoops:
    There are ways to do the same thing without Goto, but not as simply.
    IMHO, feel free to use Goto, just don't get carried away with it.
    ...
    Excellent example! You may be happy to know that there was an article in Communications of the ACM about 15 years ago that basically said the same thing.

  14. #14
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: What's wrong with GoTo

    Quote Originally Posted by moeur
    That being said, there is no reason not to use goto if it makes your code simpler as in the following example.
    VB Code:
    1. While Not Finished
    2.     For i = 1 To 100
    3.         If SomethingHappened(i) Then GoTo ExitAllLoops
    4.         DoOtherStuff
    5.     Next i
    6.     Finished = CheckStatus
    7.  Wend
    8.  MaybeDoOtherStuff
    9. ExitAllLoops:
    Whooo boy.... that's dangerous.....
    Consider this:
    Code:
    Do While Driving
      For intX = 1 to 100
        If DestinationReached Then Goto DestinationAchieved
        KeepDriving
      NExt
    Loop
    objCar.Stop
    objCar.Ingition = enmOff
    
    DestinationAchieved:
    Exit Car
    What is *wrong* with that? Can *anyone* (who advocates the use of goto) see the inherent danger (or not?) in that piece of code?

    Tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  15. #15
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: What's wrong with GoTo

    VB Code:
    1. Do While Not Finished
    2.     For i = 1 To 100
    3.         If SomethingHappened(i) Then Do
    4.         DoOtherStuff
    5.     Next i
    6.     Finished = CheckStatus
    7. Loop
    8. If Finished Then
    9.     MaybeDoOtherStuff
    10. End If
    I assume you meant Exit Do. In any case this technique adds an extra statement which can easily get out of had if the nesting gets much deeper.

    ...

  16. #16
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,632

    Re: What's wrong with GoTo

    I really hope this user doesn't mind me using their app as an example.
    But anyways download the zip file in Post 16 of the following thread:

    http://www.vbforums.com/showthread.php?t=321688

    It's worth having a look at the whole code. It's quite amazing. That user must be a genius to have written that code given all the problems with it.

    Code:
    Private Sub POP_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    POP(Index).GetData inp$
    WaitF(Index) = WaitF(Index) + inp$
    If Right$(inp$, 2) = vbCrLf Then inp$ = Left$(WaitF(Index), Len(WaitF(Index)) - 2): GoTo 6 Else Exit Sub
    
    6 'MsgBox inp$
    xp = InStr(1, inp$, " ")
    If xp = 0 Then hdr$ = inp$: inp$ = "": GoTo 4
    
    hdr$ = Left$(inp$, xp - 1)
    inp$ = Mid$(inp$, xp + 1)
    4 Select Case LCase$(hdr$) 'Parse request
        Case "user"
            Conn(Index) = inp$ 'Wait for password
            Send Index, "+OK User name received, please use PASS command to log in." + vbCrLf
            
        Case "apop"
    That is a snippet of the code from the DataArrival event of a winsock control.
    Notice how they're using "line numbers" as their goto labels. Plus, they are not even in order. Does 6 come before 2, and 1 afer 3...Errrr...Now tracing the code is getting REALLY hard.
    This is a perfect example of how not to write code.
    Oh, and they don't use Option Explicit either...Now you're really knackered trying to find bugs.

    If you want a reason not to use Gotos then that code is it.

    Woka

  17. #17
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: What's wrong with GoTo

    This is always a religious war - but I can't resist.

    The concept of moving the "program pointer" to a new location is a foundation of programming.

    Assembler could not do without this - it's paramount.

    The belief that GOTO is responsible for spaghetti code is flat out wrong - bad programmers create spaghetti code and use GOTO to make it worse.

    EXIT SUB, EXIT FUNCTION, RESUME - these are all exactly the same as GOTO - absolutely no difference whatsoever.

    We develop some "loop" extensive code here - report writer engines, student schedule algorithms - we appreciate the ability to use GOSUB - a quick way to jump to "code logic" and then return to a previous location without requiring the framing of memory that a function/sub call would do. When you are looping through 100,000 rows to produce report output - this makes a difference (in our opinion). VB.Net removed GOSUB as an option (we hear) so we will have to re-code the handful of spots we used it when we migrate (or use a lower-level language - assembler - to process this logic).

    At any rate, it's always nicer to use SELECT/CASE and BOOLEAN values and LOOPING for ease of future modifications - so GOTO really doesn't find a place when those other constructs are used instead.

  18. #18
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901

    Re: What's wrong with GoTo

    GOTO is from the days of Quick and Dirty programming. Patch it to make it work. Hence, the use in speghetti code. If it made it work, then cool.

    Not for well-though-out programs, and it's rare that you need it to make code work, unless you are adding it to a poorly designed program to begin with.


    GOTO is *usually* bad, and generally unnecessary, but not un-needed.

  19. #19
    PowerPoster
    Join Date
    Jul 2001
    Location
    Tucson, AZ
    Posts
    2,166

    Re: What's wrong with GoTo

    I'm in complete agreement with szlamany. In fact when most code is disassembled, or written in assembly, alot of statements are "JUMP" which is a GoTo.
    Disassemble one of your own programs to get a good feel.

    Like any programming instruction it has its purpose. I can remember
    when this debate stated (about 20-25 years ago). Guess what - GoTo
    is still here. In fact, sometimes you can't get to where you want without
    it.

    David

  20. #20
    Frenzied Member pnish's Avatar
    Join Date
    Aug 2002
    Location
    Tassie, Oz
    Posts
    1,918

    Re: What's wrong with GoTo

    Quote Originally Posted by dw85745
    In fact when most code is disassembled, or written in assembly, alot of statements are "JUMP" which is a GoTo.
    Spot on.
    And we all know how easy it is to debug a 500 line program written in assembler.
    Pete

    No trees were harmed in the making of this post, however a large number of electrons were greatly inconvenienced.

  21. #21
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901

    Re: What's wrong with GoTo

    GoTo's disappeared with "Structured Programming". They were commonly used in COBOL programs, despite other methods that were better, hence more 'structured'.

  22. #22
    Hyperactive Member
    Join Date
    Jun 2004
    Posts
    468

    Re: What's wrong with GoTo

    It's not that GoTo is "bad", it's just that there are so often better alternatives. IMHO, as a rule, structured programming constructs are superior to the use of GoTo. But there will always be exceptional occasions.

    Quote Originally Posted by dw85745
    when most code is disassembled, or written in assembly, alot of statements are "JUMP" which is a GoTo.
    For straight assembly, GoTo is virtually required. That's because of a general lack of better constructs in assembly, not because of any virtue held by GoTo.

    Quote Originally Posted by dw85745
    I can remember when this debate stated (about 20-25 years ago).
    1968. Go To Statement Considered Harmful by Edsger W. Dijkstra

    I like what Steve McConnell has to say about this topic in his book, Code Complete 2. On page 399, Steve writes:
    Good programming doesn't mean eliminating gotos. Methodical decomposition, refinement, and selection of control structures automatically lead to goto-free programs in most cases. Achieving goto-less code is not the aim but the outcome, and putting the focus on avoiding gotos isn't helpful.
    Last edited by bpd; Feb 9th, 2005 at 10:38 PM.

  23. #23
    Lively Member
    Join Date
    Sep 2003
    Location
    Infront of my PC
    Posts
    96

    Re: What's wrong with GoTo

    Call?
    Creator of Winamp To Nick
    2nd Prize STS Game Programming 04
    Lead Programmer: Squandy Productions


    Current Project: Winamp to Sig
    if i say something good please give me some reputation!

  24. #24
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,390

    Re: What's wrong with GoTo

    ok 1st of all i dont believe that goto is a bad thing:

    - techgnome said that this could be a prob in response to ccoder's code:

    Code:
    Do While Driving
      For intX = 1 to 100
        If DestinationReached Then Goto DestinationAchieved
        KeepDriving
      NExt
    Loop
    objCar.Stop
    objCar.Ingition = enmOff
    
    DestinationAchieved:
    Exit Car
    but ccoder didn't say the content his code was to be used in - consider this:

    Code:
    While Not AtDest
        For i = 1 To RestPoint
            If SomethingHappened(i) Then GoTo EmergencyProceadure
            RestPoint=GetNextRestPointOnTrip()
        Next i
        AtDest= CheckDest()
     Wend
     HaveLunchAtDest()
    exit sub
    EmergencyProceadure:
    also whats wrong with doing this?

    Code:
    Do While Driving
      For intX = 1 to 100
        If DestinationReached Then Goto DestinationAchieved
        KeepDriving
      NExt
    Loop
    
    DestinationAchieved:
    objCar.Stop
    objCar.Ingition = enmOff
    Exit Car
    so whats so "dangerous" now?

    also Wokawidget said that "If you want a reason not to use Gotos then that code is it." - What a stupid thing 2 say - if you want you can find bad examples of anything - that doesn't nessessarly make doing those things bad. For example i could use Wokawidget's logic and say "Person X is a bad driver - therefore driving is bad."
    I agree that in that case gotos were used in a bad way - but still goto's can make benifit your code if used correctly. ccoder provided an excelent example.

    All of that said; I also think that goto should not be used solely as a replacement for do's or for's but, if used correctly, be a compliment to them.

  25. #25
    Banned dglienna's Avatar
    Join Date
    Jun 2004
    Location
    Center of it all
    Posts
    17,901

    Re: What's wrong with GoTo

    I've seen GOTO's used in Programming Tests, using a completely made-up language. Print, Get, and GOTO! You have to figure out the value of X after it gets calculated in a midst of speghetti code. I always managed to figure out the correct answers, so as a learning tool, seeing them is good. Using them is not, usually.

  26. #26
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,632

    Re: What's wrong with GoTo

    Quote Originally Posted by i00
    also Wokawidget said that "If you want a reason not to use Gotos then that code is it." - What a stupid thing 2 say - if you want you can find bad examples of anything - that doesn't nessessarly make doing those things bad. For example i could use Wokawidget's logic and say "Person X is a bad driver - therefore driving is bad."
    True true. But I would use "Person X is a bad driver when driving drunk- alcohol is a bad thing."

    I see your point.
    I was trying to show how, if you don't write structured code, and you don't control Gotos, then your code can end up pretty messed up if you are not very carefull.

    You say potato I say potato...hmmmm doesn't really work when you write then sentence...Hahaha

    Woka

  27. #27

    Thread Starter
    Addicted Member Max_aka_NOBODY's Avatar
    Join Date
    Jul 2004
    Location
    Amman, Jordan
    Posts
    179

    Re: What's wrong with GoTo

    All that is good, but I still am with GoTo all the way.

    Here, I rebuild my whole 2000-lines read module(of many functions on the same framework as the one I posted earlier) with Do...Loop, and upon reading a file got quite a HUGE performance hit. Assuming it was a coincidence, I did a benchmark, and unless I messed something up in the whole benchmarking module, my previous GoTo method is faster.

    The Do... Loop method below gives around 1,460,000 duration per second:

    VB Code:
    1. Private Sub Performance_Test()
    2.  
    3. Dim var As Long
    4. Milliseconds = GetTickCount
    5. SetThreadPriority GetCurrentThread, THREAD_PRIORITY_HIGHEST
    6. SetPriorityClass GetCurrentProcess, HIGH_PRIORITY_CLASS
    7. Do
    8.     If GetQueueStatus(QS_HOTKEY Or QS_KEY Or QS_MOUSEBUTTON Or QS_PAINT) Then DoEvents
    9.     Frame_Count = Frame_Count + 1
    10.     If GetTickCount - Milliseconds >= Milliseconds_Per_Second Then
    11.         Get_Frames_Per_Second = Frame_Count
    12.         Caption = Get_Frames_Per_Second & " durations per second"
    13.         Frame_Count = 0
    14.         Milliseconds = GetTickCount
    15.     End If
    16.     var = 0
    17.     Select Case var
    18.     Case Is < 10000
    19.         var = var + 1
    20.     Case Is < 20000
    21.         var = var + 1
    22.     End Select
    23. Loop
    24.  
    25. End Sub

    While my GoTo method gives around 1,520,000 durations per second:

    VB Code:
    1. Private Sub Performance_Test()
    2.  
    3. Dim var As Long
    4. Milliseconds = GetTickCount
    5. SetThreadPriority GetCurrentThread, THREAD_PRIORITY_HIGHEST
    6. SetPriorityClass GetCurrentProcess, HIGH_PRIORITY_CLASS
    7. Label_01:
    8.     If GetQueueStatus(QS_HOTKEY Or QS_KEY Or QS_MOUSEBUTTON Or QS_PAINT) Then DoEvents
    9.     Frame_Count = Frame_Count + 1
    10.     If GetTickCount - Milliseconds >= Milliseconds_Per_Second Then
    11.         Get_Frames_Per_Second = Frame_Count
    12.         Caption = Get_Frames_Per_Second & " durations per second"
    13.         Frame_Count = 0
    14.         Milliseconds = GetTickCount
    15.     End If
    16.     var = 0
    17.     Select Case var
    18.     Case Is < 10000
    19.         var = var + 1
    20.         GoTo Label_01
    21.     Case Is < 20000
    22.         var = var + 1
    23.         GoTo Label_01
    24.     End Select
    25.  
    26. End Sub

    As you see, even in this micro-loop it gives quite a difference. And since my functions are intended to read files up to 100MB and break them byte-by-byte, performance is more than important.

  28. #28
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: What's wrong with GoTo

    Quote Originally Posted by bpd
    It's not that GoTo is "bad", it's just that there are so often better alternatives.
    Good programming doesn't mean eliminating gotos. Methodical decomposition, refinement, and selection of control structures automatically lead to goto-free programs in most cases. Achieving goto-less code is not the aim but the outcome, and putting the focus on avoiding gotos isn't helpful.
    BPD has summed it all up in this statement. This is the whole point.

    GOTO really is a low-level language construct - it probably makes up 25% of all "assembled" code. Every SELECT/CASE and IF/THEN/ELSE ends up being a series of ASSEMBLER JUMP statements.

    Using this low-level construct in a 3rd gen language like VB instead of using IF/THEN and SELECT/CASE means you are missing the whole point of these other constructs. A SELECT/CASE is designed to be easily added to - a new case fits in 6 months later with ease. I remember before SELECT/CASE migrated into the BASIC syntax. We were forced to use IF/THEN/ELSE - many indents - 6 months later you wanted to add to this - forget it.

    The point that spaghetti code and GOTO are really based on the fact that when revisiting code for modification if you are not fully aware of all the GOTO's above your modification point you might be adding code that will never be reached. That is a logic flaw in the program construction that has nothing to do with GOTO, but is manifested by the GOTO. The logic was failed to begin with.

    After 25 years of developing large apps that are constantly modified and enhanced we have fallen upon setting BOOLEAN variables and using them in IF/THEN statements - this allows us to add new IF's later, based on BOOLEANS above.

    Good logic - properly constructed - can only be done one way. In the end there is only one single way to construct a routine. You might be presented with 4 variations - but when it comes down to it - there is really one that would rise to the top if fully scrutinized. The goal of good logic is that it's clear and easy to follow. That leads to programs that can be maintained easily.

    Since my programming shop makes most of it's dollars off of maintenance contracts this is extremely important to us.

  29. #29

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width