Sonar给出以下代码的严重违反错误(“循环复杂性”)。以下方法用于获取特殊格式的日期,例如14-02-3(年月周)。

我该如何克服这种违规行为?

private String finalDateForProject;
public String getFinalDateForProject() {
    return finalDateForProject;
}

public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {

     String projectMonth;
        switch (month) {
            case 0:  projectMonth = "01";
                     break;
            case 1:  projectMonth = "02";
                     break;
            case 2:  projectMonth = "03";
                     break;
            case 3:  projectMonth = "04";
                     break;
            case 4:  projectMonth = "05";
                     break;
            case 5:  projectMonth = "06";
                     break;
            case 6:  projectMonth = "07";
                     break;
            case 7:  projectMonth = "08";
                     break;
            case 8:  projectMonth = "09";
                     break;
            case 9: projectMonth = "10";
                     break;
            case 10: projectMonth = "11";
                     break;
            case 11: projectMonth = "12";
                     break;
            default: projectMonth = " ";
                     break;
        }

        String yearEdited = year.toString();
        yearEdited = yearEdited.replace("20", "");


    String projectTrendDate = yearEdited +"-"+projectMonth+"-W"+weekId.toString();

            this.finalDateForProject =projectTrendDate;
}

最佳答案

我看到的降低循环复杂度的一种方法是替换switch语句。只需创建一个将月份索引映射到数字的数组或HashMap即可;

public void setFinalDateForProject(Integer year,Integer month, Integer weekId) {
    String[] months = new String[] {"01", "02", "03", "04", "05", ...}
    // Replace switch statement
    String projectMonth = months[month];
    // Rest of your code
    ...
}


解决此问题的另一种方法是使用String.format将整数转换为String来替换数字到字符串的映射。使用类似:

String projectMonth = String.format("%02d", month + 1);

关于java - 降低代码的循环复杂度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21695445/

10-10 12:32