Alternative to Nested Switch Statements in Java

java, nested, performance, switch-statement

Solution

I recommend you replace each nested switch statement with a call to a procedure which then executes the nested switch code.

Write something like this instead:

    EnumOne enumOne;
    EnumTwo enumTwo = null;
    EnumTwo enumThree = null;

    switch (enumOne)
    {
       case CASE_ONE:

          nested_switch1();

       case CASE_TWO:
       case CASE_THREE:

          nested_switch2();

          break;

       default:
          break;
    }

    nested_switch1() {
          switch (enumTwo)
          {
             case A:
                enumTwo = EnumTwo.B;
                break;
             case C:
                enumTwo = EnumTwo.D;
                break;
             default:
                break;
          }

          switch (enumThree)
          {
             case AA:
                enumTwo = EnumTwo.BB;
                break;
             case CC:
                enumTwo = EnumTwo.DD;
                break;
             default:
                break;
          }

          break;
    }

nested_switch2() {
          switch(EnumTwo)
          {
             default:
                break;
          }

          switch (enumThree)
          {
             case AA:
                enumTwo = EnumTwo.XX;
                break;
             case CC:
                enumTwo = EnumTwo.YY;
                break;
             default:
                break;
          }
}

Problem

So I wrote a method today that incorporated the use of nested switch statements, and the code looked fairly clean and concise to me, but I was told that nested switch statements are not typically the best way to go as they can get confusing with the more switch statements that you add on. Here is a sample of what my code looked like: ``` EnumOne enumOne; EnumTwo enumTwo = null; EnumTwo enumThree = null; switch (enumOne) { case CASE_ONE: switch (enumTwo){ case A: enumTwo = EnumTwo.B; break; case C: enumTwo = EnumTwo.D; break; default: break; } switch (enumThree) { case AA: enumThree = EnumTwo.BB; break; case CC: enumThree = EnumTwo.DD; break; default: break; } break; case CASE_TWO: case CASE_THREE: switch(EnumTwo) { default: break; } switch (enumThree) { case AA: enumThree = EnumTwo.XX; break; case CC: enumThree = EnumTwo.YY; break; default: break; } break; default: break; } ``` So my question would be, essentially, what would be a suitable alternative to these switch statements?

Original source