【问题标题】:Reducing cyclomatic complexity of a switch statement降低 switch 语句的圈复杂度
【发布时间】:2020-11-29 14:09:09
【问题描述】:

以下方法已被我的 IDE 标记为圈复杂度过高。我的学校要求我消除我的 IDE 可能在我的代码中抛出的所有警告,所以我想知道在这种情况下是否有一种简单的方法来做到这一点。

对于上下文,代码应该选择游戏板上的哪一列字段,其中列标记为 A 到 O 给定的字符代表。

public int getColumn(final char c) {
        switch (c) {
            case 'A':
                return 0;
            case 'B':
                return 1;
            case 'C':
                return 2;
            case 'D':
                return 3;
            case 'E':
                return 4;
            case 'F':
                return 5;
            case 'G':
                return 6;
            case 'H':
                return 7;
            case 'I':
                return 8;
            case 'J':
                return 9;
            case 'K':
                return 10;
            case 'L':
                return 11;
            case 'M':
                return 12;
            case 'N':
                return 13;
            case 'O':
                return 14;
            default:
                return -1;
        }
    }```

【问题讨论】:

    标签: java switch-statement


    【解决方案1】:

    使用哈希图将字符存储为键,将数字存储为值。

    请参考 https://www.w3schools.com/java/java_hashmap.asp 了解 hashmap 的使用

    【讨论】:

    • 默认情况下如何工作?我不需要确保密钥是 15 个有效密钥之一吗?
    • 你可以放一个简单的 if else 语句。如果映射中存在键,则返回值。否则返回 -1。
    • Hashmap 是多余的 - 所需的功能只是英文字母表中字母的(基于 0 的)位置。另一个答案要简单得多。
    【解决方案2】:

    或者滥用字符表示为数字的事实:

    public int getColumn(final char c) {
        if((c >= 'A') && (c <= 'O')) {
            return c - 'A';
        }
        else {
            return -1;
        }
    }
    

    【讨论】:

    • 这不是“滥用”——这是最合理的做法!
    【解决方案3】:

    我不确定这是否适用于您的上下文,但为什么不直接使用 ASCII 字符表?

    你可以把它转换成一个整数,因为大写的 A 字符是索引 65,你可以从中减去 65。

    例如:

    public int getColumn(final char c) {
        int index = (int) c;
    
        if (index > (int) 'O') {
            return -1;
        }
    
        return index - (int) 'A';
    }
    

    【讨论】:

      【解决方案4】:

      使用地图可以做到:

      Map<Character, Integer> columnMap = ImmutableMap
           .of('A', 0, 'B', 1, 'C',3);//Or any other initialization way
      
      public int getColumn(final char c) {
          return columnMap.getOrDefault(c, -1);//-1 default value if letter not found
      }
      

      或者,如果您只想获取大写字母在字母表中的位置,请使用:

      public int getColumn(final char c) {
          return (int)c - 'A';
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 2020-10-03
        • 1970-01-01
        相关资源
        最近更新 更多