Java 中嵌套 switch 语句的替代方案

2022-01-19 00:00:00 performance nested switch-statement java

所以我今天写了一个方法,它结合了嵌套 switch 语句的使用,代码在我看来相当干净简洁,但有人告诉我嵌套 switch 语句通常不是最好的方法,因为它们会让人感到困惑使用您添加的更多 switch 语句.这是我的代码的示例:

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;
}

所以我的问题是,基本上,这些 switch 语句的合适替代方案是什么?

So my question would be, essentially, what would be a suitable alternative to these switch statements?

推荐答案

我建议您将每个嵌套的 switch 语句替换为对然后执行嵌套 switch 代码的过程的调用.

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

改为这样写:

    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;
          }
}

相关文章