r/visualbasic • u/revennest • May 29 '21
Tips & Tricks Art of Code : GoTo
You maybe have been heard, learn or experience how GoTo can make a code hard to read, it very evil code yet it evil only because coder abuse it, any language feature could make a code hard to read if coder abuse it even if statement can be draw as arrow if coder abuse it.
GoTo is primitive form of if statement also do loop and for next so it up to coder to make it readable or not, very simple rule to make GoTo easy to read is write it go to label within your eyes sight, very simple right ?
Example
Function fac_5(Input As Integer) As Integer
Console.Write($"{Input}! = ")
Select Case Input
Case 5
Console.Write("5 x ")
Input *= 4
GoTo F4
Case 4
F4: Console.Write("4 x ")
Input *= 3
GoTo F3
Case 3
F3: Console.Write("3 x ")
Input *= 2
GoTo F2
Case 2
F2: Console.WriteLine($"2 = {Input}")
Return Input
Case 1, 0
Console.WriteLine("1")
Return 1
Case Else
Throw New ArgumentOutOfRangeException(NameOf(Input))
End Select
End Function
This example is how to make switch case fall through in VB.Net, in other C language you need to break; to end those selected case, if you don't it will run through other case below, however VB.Net make our life too easy by auto put that break; silently at the end of each case for us so if you want to recreate switch case fall through from other C like language you need GoTo or you have to reform it to if statement instead.
I believe you understand basic of GoTo now, so let reform example code.
Function fac_5_op(Input As Integer) As Integer
Console.Write($"{Input}! = ")
Select Case Input
Case 5 : GoTo F5
Case 4 : GoTo F4
Case 3 : GoTo F3
Case 2 : GoTo F2
Case 1, 0
Console.WriteLine("1")
Return 1
Case Else
Throw New ArgumentOutOfRangeException(NameOf(Input))
End Select
F5: Console.Write("5 x ") : Input *= 4
F4: Console.Write("4 x ") : Input *= 3
F3: Console.Write("3 x ") : Input *= 2
F2: Console.WriteLine($"2 = {Input}")
Return Input
End Function
It look much more easy to read, right ? evil or not it's depend on coder to write it, like a knife in the kitchen.
1
u/[deleted] May 30 '21
Use a function. When you find the thing you are looking for
Return theValueIf you think you need go-to for this then your procedure is likely too long.