Is goto ok for breaking out of nested loops?

后端 未结 10 1838
忘掉有多难
忘掉有多难 2021-01-18 04:33

JavaScript supports a goto like syntax for breaking out of nested loops. It\'s not a great idea in general, but it\'s considered acceptable practice. C# does not directly

相关标签:
10条回答
  • 2021-01-18 05:14

    IMO it is acceptable in languages that do not support break n; where n specifies the number of loops it should break out.
    At least it's much more readable than setting a variable that is then checked in the outer loop.

    0 讨论(0)
  • 2021-01-18 05:15

    anonymous functions

    You can almost always bust out the inner loop to an anonymous function or lambda. Here you can see where the function used to be an inner loop, where I would have had to use GoTo.

    private void CopyFormPropertiesAndValues()
    {
        MergeOperationsContext context = new MergeOperationsContext() { GroupRoot = _groupRoot, FormMerged = MergedItem };
        // set up filter functions caller
        var CheckFilters = (string key, string value) =>
        {
            foreach (var FieldFilter in MergeOperationsFieldFilters)
            {
                if (!FieldFilter(key, value, context))
                    return false;
            }
            return true;
        };
        // Copy values from form to FormMerged 
        foreach (var key in _form.ValueList.Keys)
        {
            var MyValue = _form.ValueList(key);
            if (CheckFilters(key, MyValue))
                MergedItem.ValueList(key) = MyValue;
        }
    }
    

    This often occurs when searching for multiple items in a dataset manually, as well. Sad to say the proper use of goto is better than Booleans/flags, from a clarity standpoint, but this is more clear than either and avoids the taunts of your co-workers.

    For high-performance situations, a goto would be fitting, however, but only by 1%, let's be honest here...

    0 讨论(0)
  • 2021-01-18 05:18

    Unacceptable in C#.

    Just wrap the loop in a function and use return.

    EDIT: On SO, downvoting is used to on incorrect answers, and not on answers you disagree with. As the OP explicitly asked "is it acceptable?", answering "unacceptable" is not incorrect (although you might disagree).

    0 讨论(0)
  • 2021-01-18 05:21

    I would personally try to avoid using goto here by simply putting the loop into a different method - while you can't easily break out of a particular level of loop, you can easily return from a method at any point.

    In my experience this approach has usually led to simpler and more readable code with shorter methods (doing one particular job) in general.

    0 讨论(0)
提交回复
热议问题