Search code examples
c#vb6labelgoto

Acceptable use of GoTo?


I'm currently rewriting an old VB6 program in C# in the .Net Framework 2.0 (not my choice, it was decided by the company). For the most part, things have gone pretty well. The program measures incoming data from a precision grinding machine and displays graphs and dials to display the accuracy.

The original programmer was a mechanical engineer, however, not a software engineer. The program works, but there's a bit of sloppy code here and there. Most notably, I've run into a few GoTo statements. It's been pretty easy to just stick things in a loop, where necessary, and get the same functionality out of it.

I've run up against a case in the original code, however, where it seems like the GoTo is doing more than just simulating a loop. It has a couple different exit conditions. It looks something like this (not the actual code, just something short I made up to demonstrate):

VB6 Code

Public Sub Tick()
    Dim condition1 As Boolean
    Dim condition2 As Boolean
    Dim testNumber As Integer

    beginning:    'The GoTo label'

    ' (... Some Other Code Here ...)'

    If condition1 = True Then
        goto beginning
    Else
        ' (... Do some calculation ...)'
    End If

    If condition2 = True Then
        ' (... Do some calculation ...)'
        goto beginning
    End If

    Select Case testNumber
        Case 1: '(... Some code ...)'
        Case 2: '(... Some code ...)'
        Case 3: '(... Some code ...)'
        Case 4: goto beginning
    End Select
End Sub

The actual code might have a few less conditions than that, but the basic idea is that there are a few different things that cause it to loop back on itself. Is there a good way to go about writing a loop for a situation like that, or is this a case in which a goto statement would be acceptable? (Admittedly, a non-goto solution would be preferred).

Thanks for your time and consideration.

Note: I tried using a while(true) loop with a break; statement, but it caused the program to get caught in an infinite loop and lock up. Would it be more advised to write a long while loop containing several conditions (with and/or, etc.)?


Solution

  • A while(true) loop should be fine, if you have a break at the end of it and continue wherever there was previously a goto. However, this should definitely only be the first step - it sounds like a vigorous refactoring is called for.