更新时间:2022-09-13 11:24:45
代码的环复杂度(Cyclomatic complexity,有时也翻译成圈复杂度)是一种代码复杂度的衡量标准,在1976年由Thomas J. McCabe, Sr. 提出。
来看看计算公式。
代码环复杂度 = E − N + 2
E = 程序控制流图中边的个数
N = 程序控制流图中点的个数
很容易得出这样的结论:代码环复杂度越高,越容易出bug。
可以想象如果需要开发人员自己去把一段代码的控制流图画出来,然后去数图中边和点的个数,这种做法效率太低了也容易出错。
好消息是,有一款名为Source Monitor的免费软件,能够帮我们来度量Java代码的环复杂度。当然这款软件也支持C++和C#。
为了说明如何使用这款软件,我写了一段简单的Java代码。
package test; import java.util.ArrayList; public class monthTool { static ArrayList<String> monthCollection = new ArrayList<String>(); public static void main(String[] args) { monthTool tool = new monthTool(); tool.printV1(1); tool.printV2(2); tool.printV1(0); tool.printV2(-1); tool.printV3(3); tool.printV3(13); } public monthTool(){ monthCollection.add("Invalid"); monthCollection.add("January"); monthCollection.add("Febrary"); monthCollection.add("March"); monthCollection.add("April"); monthCollection.add("May"); monthCollection.add("June"); monthCollection.add("July"); monthCollection.add("August"); monthCollection.add("September"); monthCollection.add("October"); monthCollection.add("November"); monthCollection.add("December"); } public void printV1(int month){ System.out.println("Month is: " + getMonthNameV1(month)); } public void printV2(int month){ if( month >= 1 && month <= 12) System.out.println("Month is: " + getMonthNameV2(month)); else System.out.println("Please specify a valid month"); } public void printV3(int month) { System.out.println("Month is: " + getMonthNameV3(month)); } public String getMonthNameV2(int month){ if( month == 1) return "January"; else if( month == 2) return "Febrary"; else if( month == 3) return "March"; else if( month == 4) return "April"; else if( month == 5) return "May"; else if( month == 6) return "June"; else if( month == 7) return "July"; else if( month == 8) return "August"; else if( month == 9) return "September"; else if( month == 10) return "October"; else if( month == 11) return "November"; else if( month == 12) return "December"; else return "Invalid"; } public String getMonthNameV1(int month){ switch (month){ case 1: return "January"; case 2: return "Febrary"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return "Invalid"; } } public String getMonthNameV3(int month){ try { return monthCollection.get(month); } catch (java.lang.IndexOutOfBoundsException e){ return "Invalid"; } } }
其中我用了三种不同的方式实现了同一个逻辑,将一个代表月份的整数转成了月份名称。
下面是Source Monitor的具体用法。
1. 创建一个新的项目: