Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get rid of this goto?

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: ;
}
like image 972
HireThisMarine Avatar asked Dec 06 '25 00:12

HireThisMarine


2 Answers

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.

like image 112
Yacoub Massad Avatar answered Dec 07 '25 13:12

Yacoub Massad


Move the inner loop to a method, and conditionally break based on its return value.

like image 34
Cecilio Pardo Avatar answered Dec 07 '25 12:12

Cecilio Pardo