I've posted a code snippet on another forum asking for help and people pointed out to me that using GoTo
statements is very bad programming practice. I'm wondering: why is it bad?
What alternatives to GoTo
are there to use in VB.NET that would be considered generally more of a better practice?
Consider this snippet below where the user has to input their date of birth. If the month/date/year are invalid or unrealistic, I'd like to loop back and ask the user again. (I'm using if statements to check the integer's size... if there's a better way to do this, I'd appreciate if you could tell me that also :D)
retryday:
Console.WriteLine("Please enter the day you were born : ")
day = Console.ReadLine
If day > 31 Or day < 1 Then
Console.WriteLine("Please enter a valid day")
GoTo retryday
End If
Questions about the merits of the
GoTo
statement (or rather the lack thereof) are perennial on this site. Click here for an example: Is GoTo still considered harmful?With regards to an alternative to
GoTo
, in the provided snippet, awhile
loop would nicely do the trick, maybe something like:It is often recommended that we follow Dijkstra's advice in Go-To Statement Considered Harmful.
Donald Knuth answered Dijkstra pretty soundly. This example here is a modern version of one of his counterexamples. Personally I write infinite loops with internal breaks when I encounter this one but there's a few other rare cases where I will write GOTO statements.
The most common ones for me are breaking out of deeply nested loops and this pattern:
I also have two cases of large finite state machines with goto statements providing the transitions.
You can do almost anything that you can do with
GOTO
s with simple built-in language constructs like decision structures and loops, andGOTO
statements often make for messy, impossible-to-understand spaghetti code. Loops and ifs and such have a clear, accepted, understandable usage.See, as is usually suggested, Dijkstra's Go-To Statement Considered Harmful
GOTOs are a pretty political issue. The 'solution' to GOTOs is to use other built-in navigation constructs like functions, methods, loops, etc. For VB, you could make a sub-procedure that runs that code, or put it in a While loop. You can google both of those subjects fairly easily.
A little clunky but:
Also consider some basic loops in "goto land"
Here's the nice equivalent:
Which is more readable and less error prone?