Coding Review – How would you convert this ‘goto’ ?


This is a legacy code snippet that uses the magic goto, which I find it very difficult to understand and refactor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
doit:
   foreach (var line in dict.Values)
    {
        var pts = new List<PointF>();
        var rm = new Dictionary<string, LineData>();
 
        doSomething(line, dict, pts, ref rm);
        doSomethingWith(pts);
 
        foreach (var item in rm.Values)
        {
            dict.Remove(item.ToString());
        }
 
        goto doit;
    }
doit:
   foreach (var line in dict.Values)
    {
        var pts = new List<PointF>();
        var rm = new Dictionary<string, LineData>();

        doSomething(line, dict, pts, ref rm);
        doSomethingWith(pts);

        foreach (var item in rm.Values)
        {
            dict.Remove(item.ToString());
        }

        goto doit;
    }

The goto doit jumps outside the loop. It isn’t that bad because dict will eventually be cleared so that it does not cause endless loop.

Each iteration, the items from rm have been removed in dict until no more items are found, so this could be rewritten in something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
while (dict.Count > 0) {
    var line = dict.Take(1);
    var pts = new List<PointF>();
    var rm = new Dictionary<string, LineData>();
 
    doSomething(line, dict, pts, ref rm);
    doSomethingWith(pts);
 
    foreach (var item in rm.Values)
    {
        dict.Remove(item.ToString());
    }
}
while (dict.Count > 0) {
    var line = dict.Take(1);
    var pts = new List<PointF>();
    var rm = new Dictionary<string, LineData>();

    doSomething(line, dict, pts, ref rm);
    doSomethingWith(pts);

    foreach (var item in rm.Values)
    {
        dict.Remove(item.ToString());
    }
}

The Take works for IEnumerable and it takes a number of items from the dict object.

How would you rewrite this goto?

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
251 words
Last Post: How to Download Video from ted.com in Javascript?
Next Post: The Future of AI in the Gaming Industry

The Permanent URL is: Coding Review – How would you convert this ‘goto’ ?

Leave a Reply