Simulate `goto`

9 views
Skip to first unread message

zhong...@gmail.com

unread,
Sep 25, 2015, 2:29:46 PM9/25/15
to java.lang.fans
(an answer I wrote to an SO question, which is then deleted)

`goto` is great in modeling a complex flow chart :) which java doesn't allow. There are several ways to simulate that. One way is to use `switch` to jump



    while(state!=DONE)
    {
        switch(state)
        {
            ...

            case FOO:

                do something;

                state = BAR; break; // goto BAR

            ...

            case BAR:
                ...

            ...
        }
    }

Another way is to use tail call

    void foo()
    {
        ...
        bar(); // goto bar
    }
    void bar()
       ...

However this may cause stackoverflow, since java doesn't do tail call optmization yet. There have been talks to introduce it in java, like

    void foo()
    {
        ...
        goto bar();
    }


We can simulate tail call optimization by so called "trampoline"

    State foo(){ ... return BAR; }

    while(state!=DONE)
    {
        switch(state)
        { 
            case FOO : state=foo(); break;
            case BAR : state=bar(); break;
          ...


Or, we could encap each substate in its own type


    class Foo implements Step
    {
        Step progress()
        {
            ...
            return new Bar(args);
        }
     }

     while(!(step instanceof End))
     {
         step = step.progress();
     }

In java8, we may do it more succinctly

    Step foo = ()->
    {
        ...
        return bar;
    }
    Step bar = ...


    // main
        step = start;
        while(step!=end)
            step = step.progress();
           
However, the explict-class-per-step approach (`class Foo implements Step`) has the advantage that Foo can store all state variables needed by Foo, and nothing more. This makes it easy to understand the flow. In other approaches, all state variables for all steps are present at the same time, making it quite confusing.


Zhong Yu
bayou.io







          
Reply all
Reply to author
Forward
0 new messages