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
I'm going to differ from everyone else and say that GOTOs themselves are not all the evil. The evil comes from the misuse of GOTO.
In general, there is almost always better solutions than using a GOTO, but there really are times when GOTO is the proper way to do it.
That being said, you are a beginner, so you shouldn't be allowed to judge if GOTO is proper or not (because it hardly ever is) for a few more years.
I would write your code like this (my VB is a bit rusty...):
Dim valid As Boolean = False
While Not valid
Console.WriteLine("Please enter the day you were born: ")
Dim day As String
day = Console.ReadLine
If day > 31 Or day < 1 Then
Console.WriteLine("Please enter a valid day.")
Else
valid = True
End If
End While
If you take your GOTO code and look at it, how would someone first approach your code? "Hmm.. retryday? What does this do? When does this happen? Oh, so we goto that label if the day is out of range. Ok, so we want to loop until the date is considered to be valid and in range".
Whereas if you look at mine:
"Oh, we want to keep doing this until it's Valid. It is valid when the date is within range."
http://xkcd.com/292/ I think this is the standard opinion of GoTo
.
Instead, try and use a Do Until
loop. Do Until
loops will always execute once and are great when you need to prompt the user and want to make sure that you do not proceed until they enter the correct information.
Sub Main()
'Every time the loop runs, this variable will tell whether
'the user has finally entered a proper value.
Dim Valid As Boolean = False
'This is the variable which stores the final number which user enters.
Dim Day As Integer = 0
Do Until Valid
Console.WriteLine("Enter the day:")
Dim DayStr As String = Console.ReadLine()
If Not Integer.TryParse(DayStr, Day) Then
Console.WriteLine("Invalid value! It must be a valid number.")
Valid = False
ElseIf (Day < 1) Or (Day > 31) Then
onsole.WriteLine("Invalid day! It must be from 1 to 31.")
Valid = False
Else
Valid = True
End If
Loop
'blablabla
'Do whatever you want, with the Day variable
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With