I just started a position and at the end of the workday I wait out traffic by slowly reading through our codebase. I came across this bit and even after a fair amount of time at the whiteboard I still can't think of a way to extract the goto. Is there a way to excise this jump?
public void MyUpdate(MyType foo)
{
/*Prep code for the loops*/
foreach (Thing bar in something)
{
foreach (Collection item in bar.Stuff)
{
Data dataRX = item.First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
goto exitLoops;
}
}
}
exitLoops: ;
}
Since the label exitLoops is at the end of the method, then you can simply use return to exit the method like this:
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
return;
}
Another approach is to use a flag like this:
bool done = false;
foreach (Thing bar in something)
{
foreach (Collection item in bar.Stuff)
{
Data dataRX = item.First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
done = true;
break;
}
}
if(done)
break;
}
You can use the second approach even if there is some code after the label.
Move the inner loop to a method, and conditionally break based on its return value.
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