Reputation: 788
I have a System.Data.DataTable of zoo animals (SomeZoo), and I want to find a particular animal by his/her name.
For each Animal in SomeZoo.Rows
if not (Animal("Name").ToString = Given_Name) Then
SomeZoo.Rows.Remove(Animal)
else
continue for
End if
I have a friend who says that the "continue for" to break the if statement and go back to sorting out animal names that don't match is 'bad practice'. What a fool.
Anyways, is he right? Is breaking an if statement with 'Continue For' inside of a For each loop a 'bad practice'? He even compared it to a 'goto'.
Thanks!
Upvotes: 1
Views: 143
Reputation: 1093
I look at Continue For as a good alternative to the bad option of Goto. Do the Continue For naysayers also view Exit For as bad practice? I don't see how one could hold that one is acceptable and the other is not. Yes, they are technically syntactic sugar, but if you think that's a bad thing, why are you coding in VB? They are at times preferable to a high order of nested if statements and/or creating otherwise unnecessary Booleans only to check whether or not to complete the rest of the loop. They become even more useful (in terms of reducing the effort you must spend to achieve a result, which I'm arguing is the point) if used to break a loop outside of the innermost one it is used in.(See this link.)
As far as when to use them, a rule of thumb is whenever doing so will make your code lighter and easier to understand. I've got a search form with over a dozen listboxes the user can use to limit results, with more listboxes and values likely to be added in the future. Coding that form without a Continue For would have meant a ridiculous amount of nested If statements or a SQL command with over a dozen joins, neither of which I care to encounter a couple of months from now when I need to add one more validation check. Instead I use a Continue For whenever a record fails a condition before loading it into the results and go on enjoying my life. (In this scenario, I am able to limit the records I loop through to a very manageable number with two simple conditions, and most of my other checks are fairly complex.)
Upvotes: 1
Reputation: 426
In your example code it seems pointless and convoluted, but there are good uses for continue for. Note: The example code will error once a removal is done. Maybe try the below.
For i As Integer = SomeZoo.Rows.Count - 1 To 0 Step -1
If Not SomeZoo.Rows(i)("Name").ToString = Given_Name) Then SomeZoo.Rows.Remove(SomeZoo.Rows(i))
Next
Upvotes: 1