CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 28
  1. #1
    Join Date
    Oct 2006
    Posts
    28

    Good Programming practice- using goto

    OK, I know using GOTO is ugly old programming, but what is a better solution?

    I give my user an OpenFileDialog and allow them to choose a file.
    If I don't like the file they have chosen I give them a message explaining why and send them back using GOTO to choose again.

    What would be a more elegant way of doing this?
    I'm using .NET Framework 3.5

    I'm planning to be spontaneous tomorrow

  2. #2
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Good Programming practice- using goto

    Select Case, Try Catch with a flag, and when absolutely necessary, one GOTO statement isn't really bad.

    What made them bad, was using them to control the execution of the program. There could be 5 in one sub, just to get out of the sub.

    Following around the logic was known as 'spaghetti code' for that reason
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  3. #3
    Join Date
    Dec 2007
    Posts
    234

    Re: Good Programming practice- using goto

    I'd go for a loop with a flag and select case... the problem I have with goto is that "what harm can one little goto do?" ends up being repeated several times, and can lead to hard to follow code (good old fashioned spaghetti code). If used minimally, and properly, there's generally no problem with it. Unfortunately developers tend to lack restraint when using something so simple.

    -tg

    edit - yes, I'm guilty of having writ my share of spaghetti code in the past.
    * I don't respond to private requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help - how to remove 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???
    * On Error Resume Next is error ignoring, not error handling(tm). * Use Offensive Programming, not Defensive Programming.
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN
    MVP '06-'10

  4. #4
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Good Programming practice- using goto

    I had a DrawPoker game in Quick Basic, which worked, but didn't use many functions or subs that didn't have a GOTO it there. Usually just to jump to the end of the module, or call a model form.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  5. #5
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Good Programming practice- using goto

    For the most part Goto should only be used as part of the On Error statement. (VB6)
    Loops, sub routines, functions are better choices for other code.

    That said an occasional Goto is not a show stopper.
    Last edited by DataMiser; July 27th, 2010 at 11:18 AM.
    Always use [code][/code] tags when posting code.

  6. #6
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Good Programming practice- using goto

    So long as the execution flow is low or not critical GoTo would be okay, although I don't use it at all, since you are looping until a condition is met, so why not use Do, or For loops.

    However, I believe you are looking for the way to cancel the ok button.
    Essentially right?
    With a visual openfiledialog control on the form:
    Code:
        Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
          'If file is not good(this test app)
            If IO.Path.GetFileName(OpenFileDialog1.FileName) = "WindowsApplication1.exe" Then
                e.Cancel = True
                   MessageBox.Show("Can't point to this file for example")
            End If
        End Sub
    Last edited by TT(n); July 27th, 2010 at 11:49 AM.

  7. #7
    Join Date
    Dec 2009
    Posts
    596

    Re: Good Programming practice- using goto

    After the messagebox can't we just do a Exit sub?

  8. #8
    Join Date
    Dec 2007
    Posts
    234

    Re: Good Programming practice- using goto

    you could .... *I* don't... I subscribe to the Single-Entry, Single-Exit design when it comes to Subs/Methods/Functions. Meaning there's one point of entry, and one place, and one place only, where the s/m/f exits, and Exit Sub violates that. That's not to say using Exit Sub is bad, I just tend to avoid it if I can.

    -tg
    * I don't respond to private requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help - how to remove 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???
    * On Error Resume Next is error ignoring, not error handling(tm). * Use Offensive Programming, not Defensive Programming.
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN
    MVP '06-'10

  9. #9
    Join Date
    Dec 2009
    Posts
    596

    Re: Good Programming practice- using goto

    Hmmm I never thought about it that way. Good to know of that angle.

  10. #10
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Good Programming practice- using goto

    Yep, I do not like to use exit sub much either.
    In an instance like we have here a simple loop would work fine. Something like
    Code:
    Do
        GetFileName
        If Filename Ok then 
            Exit Do
        Else
            Message
        End If
    Loop
    Always use [code][/code] tags when posting code.

  11. #11
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Good Programming practice- using goto

    Well here we figured out that there isn't a need for a loop in this request.

    Wrong file, so cancel ok(open) in .NET way, inform user to try again.
    Elegant.

  12. #12
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,284

    Re: Good Programming practice- using goto

    While we're on the topic of "the good, the bad, and the ugly" coding practices, a thin that irritates em is when people make use of an empty catch block. Meaning, they have something like this :

    Code:
    Try
    'Do stuff
    Catch ex As Exception
    
    End Try
    What are your thoughts on this ?

  13. #13
    Join Date
    Jun 2004
    Location
    NH
    Posts
    678

    Re: Good Programming practice- using goto

    Here is my view.

    I've seen empty catches too, usually in examples where the coder may not have wanted to put in custom error handling in a generic example. It's up to you. I may have done it myself once or twice.

    Although sometimes, it may be used like that to ignore a nasty framework error message, or some other undesirable chain of events.
    While only if the message is worst than what happens if ignoring the error.
    One should always be mindful of the worse case scenario, before ignoring an error.
    EDIT: For example WaitForInputIdle API can fail with certain process handles and conditions(non graphic),
    so Try/Catch/Ignore is a way to ommit the nasty hanging error, which was worse than not waiting... it didn't need to wait to begin with, and should have been ignored.
    Although a full defensive technique, would check for graphical interface first before even trying.

    Try Catch Ignore, behaves slightly different than On Error Resume Next ofcourse.
    A Try Catch block can stubbornly lock up and refuse to try "ever" again, with certain various errors, until restarted.

    Usually when I use On Error Resume Next, the code doesn't even need any error handling, which does cause some coders to snap to judgment, and frown on the rest of your work.
    I may use it as intended with defensive styles, but usually to cover for unforseen errors, hardware errors, or solar flares etc. It's always placed last in those cases. I try not to catch an error late, in favor of defensive programming techniques, return values, file checking etc.
    Last edited by TT(n); July 28th, 2010 at 02:26 AM.

  14. #14
    Join Date
    Jun 2005
    Location
    JHB South Africa
    Posts
    3,772

    Re: Good Programming practice- using goto

    On the subject of Empty Try Catch blocks.. i often use it to check for the existence of a Device, or SQL.
    Something like...
    Code:
            Public Shared Function TestConnectionString(ByVal ConnectionString As String) As Boolean
                Dim Reply As Boolean
                Try
                    Dim sqlConn As New SqlConnection(ConnectionString)
                    sqlConn.Open()
                    Reply = True
                    sqlConn.Close()
                Catch ex As Exception
                    Reply = False
                End Try
                Return Reply
            End Function
    Here i'm realy not interested in what the error was, Just that the SQL connection string did not work.

    I've built similar functions to search for external USB or COM devices, and it helps to use these just before committing to some intricate function that may hang the system if the device is not responding..
    Articles VB6 : Break the 2G limit - Animation 1, 2 VB.NET : 2005/8 : Moving Images , Animation 1 , 2 , 3 , User Controls
    WPF Articles : 3D Animation 1 , 2 , 3
    Code snips: VB6 Hex Edit, IP Chat, Copy Prot., Crop, Zoom : .NET IP Chat (V4), Adv. ContextMenus, click Hotspot, Scroll Controls
    Find me in ASP.NET., VB6., VB.NET , Writing Articles, My Genealogy, Forum
    All VS.NET: posts refer to VS.NET 2008 (Pro) unless otherwise stated.

  15. #15
    Join Date
    Jul 2010
    Location
    Watch Window
    Posts
    87

    Thumbs up Re: Good Programming practice- using goto

    Here i'm realy not interested in what the error was, Just that the SQL connection string did not work.
    you have missed return of any function.
    Code:
    public Shared Function TestConnectionString(ByVal ConnectionString As String) As Boolean
                Dim Reply As Boolean
                Try
                    Dim sqlConn As New SqlConnection(ConnectionString)
                    sqlConn.Open()
                    return True
                    sqlConn.Close()
                Catch ex As Exception
                   Return false
                End Try
                Return Reply
    
            End Function

Page 1 of 2 12 LastLast

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

Featured