用间隔减少环形复杂性

时间:2013-05-24 06:12:49

标签: java cyclomatic-complexity

以下java代码给出了相当高的Cyclomatic Complexity。我想找到一种方法来适当减少它。我最好怎么做?

要清楚,代码会根据值是否介于两个限制之间来获取值的相应结果。值本身可以是介于-10000到+200000之间的任何整数。问题主要在于“小于或等于”运算符,这会阻止简单使用库。两个限制之间的范围可以是不同的,我们在10,000s中讨论范围,示例间隔将是[< 0 ... 10000 ...... 25000 ... 32500 ...]。范围是相当随意的数字,由业务决定。

您可以假设LIMIT值是常量,在类的开头定义。设定的结果值也是如此。可以将它们从常数更改为其他内容。

有什么想法吗?

private int function getBasedOnInterval(int value){
  int result;
  if(value <= 0){
    result = RESULT1;
  }else if(value <= LIMIT1){
    result = RESULT2;
  }else if(value <= LIMIT2){
    result = RESULT3;
  }else if(value <= LIMIT3){
    result = RESULT4;
  }else if(value <= LIMIT4){
    result = RESULT5;
  }else if(value <= LIMIT5){
    result = RESULT6;
  }else if(value <= LIMIT6){
    result = RESULT7;
  }else if(value <= LIMIT7){
    result = RESULT8;
  }else if(value <= LIMIT8){
    result = RESULT9;
  }else if(value <= LIMIT9){
    result = RESULT10;
  }else if(value <= LIMIT10){
    result = RESULT11;
  }else if(value <= LIMIT11){
    result = RESULT12;
  }else if(value <= LIMIT12){
    result = RESULT13;
  }else if(value <= LIMIT13){
    result = RESULT14;
  }else{
    result = RESULT15;
  }
  return result;
}

2 个答案:

答案 0 :(得分:2)

重构这个的第一步可能是将所有限制放入数组或列表中,然后迭代它并测试每个限制:

private int function getBasedOnInterval(int value) {
    int result = RESULT15;

    // consider LIMITS as an array containing 0, LIMIT1...LIMIT13
    // consider RESULTS as an array containing RESULT1...RESULT14
    for(int index = 0; index < LIMITS.length; index++) {
        if(value <= LIMITS[index]) {
            result = RESULTS[index];
            breaks;
        }
    }

    return result;
}

答案 1 :(得分:1)

您可能正在寻找BST (Binary Search Tree)

来自维基百科;大O符号的时间复杂度:

       | Average  | Worst case
----------------------------------
Space  | O(n)     | O(n)
Search | O(log n) | O(n)
Insert | O(log n) | O(n)
Delete | O(log n) | O(n)

如果您在开始时创建一次BST并且只是重复使用它,这将允许您加快搜索速度。如果您要向我们提供有关数据传播的更多信息,可以使用其他技术进行改进

相关问题