the infame Goto, Java, automatic code

200 Views Asked by At

Imagine you have a Java code like this :

public class MyClass {
    public static Object doSmthg(Object A,Object B){
        if(smthg){ //if is given has an example, it can be any thing else
            doSmthg;
            GOTO label;
        }
        doSmthg;

        label;
        dosmthg1(modifying A and B);
        return an Object;
    }
}

I am generating the Code automatically. When the generator arrive at the moment of generating the goto (and it does not know it is in the if block), it has no knowledge of what will be afterwards.

I tried using labels,break,continue but this does not work.

I tried to use an internal class (doing dosmthg1) but A and B must be declared final. The problem is A and B have to be modified.

If there is no other solutions, I will have to propagate more knowledge in my generator. But I would prefer a simpler solution.

Any ideas ?

Thanks in advance.

3

There are 3 best solutions below

2
On
public static Object doSmthg(Object A,Object B){
    try {
    if(smthg){ //if is given has an example, it can be any thing else
        doSmthg;
        throw new GotoException(1);
    }
    doSmthg;

    } catch (GotoException e) {
         e.decrementLevel();
        if (e.getLevel() > 0)
            throw e;
    }
    dosmthg1(modifying A and B);
    return an Object;
}

One can do gotos with exception, but for targeting the correct "label" one either has to check the exception message or think of a nesting level.

I do not know whether I find this not uglier.

0
On

You can add a dummy loop around the block preceding the label, and use labeled break as an equivalent of goto:

public static Object doSmthg(Object A,Object B){
    label:
    do { // Labeled dummy loop
        if(smthg){ //if is given has an example, it can be any thing else
            doSmthg;
            break label; // This brings you to the point after the labeled loop
        }
        doSmthg;
    } while (false); // This is not really a loop: it goes through only once
    dosmthg1(modifying A and B);
    return an Object;
}
3
On

If you want to jump over something, like so:

A
if cond goto c;
B
c: C

you can do this like

while (true) {
    A
    if cond break;
    B
}
C