Cyclomatic Complexity Philippe CHARMAN charmanfr ibm com http
Cyclomatic Complexity Philippe CHARMAN charman@fr. ibm. com http: //users. polytech. unice. fr/~charman/ Last update: 04 -02 -2013
Control Flow Graph • Definition: representation, using graph notation, of all paths that might be traversed through a program during its execution • Node – Function node: f – Predicate node: c – Empty nodes: entry exit • Edge: – connection between 2 nodes, – represents the flow of control between 2 nodes
Control Flow Graph entry f c f f exit
Cyclomatic Complexity • Cyclomatic complexity is a software metric developed by Mc. Cabe in 1976 and is used to indicate the complexity of a program • The cyclomatic complexity v(G) of a single function/method is equal to: v(G) = E − N + 2 where E = the number of edges N = the number of nodes
Example #1 entry int f 1(int x){ return x+1; } x+1 exit E=2 N=3 v(G) = 2 – 3 + 2 = 1
Example #2 entry int f 2(int x, int y) { x = a(); y = b(); return x+y; } x=a() y=b() x+y exit E=4 N=5 v(G) = 1
Example #3 entry void f 3(int x) { if (x == 0) g(); else h(); } true if false h() g() exit E=6 N=6 v(G) = 2
Example #4 entry false void f 4(int x) { if (x == 0) g(); } if true g() exit E=5 N=5 v(G) = 2
Example #5 entry void f 5(int x) { if (x == 0) return; else h(); } true if false h() exit E=5 N=5 v(G) = 2
Example #6 entry void f 6(int x) { if (x > 0) a(); else b(); if (odd (x)) c(); else d(); true if b() a() true false if false d() c() } exit E = 11 N = 10 v(G) = 3
Example #7 void f 7(int x, int y) { if (x > 0) { if (y > 0) a(); else b(); } else { if (y > 0) c(); else d(); } } entry true a() if if false true b() c() exit if false d() E = 14 N = 12 v(G) = 4
Example #8 entry switch void f 8(int x) { switch (x) { case 0: a(); break; case 1: b(); break(); case 2: c(); break; } } a() b() c() exit E = 10 N=8 v(G) = 4
Example #9 entry if void f 9(int x) { if (x == 0) a(); if (x == 1) b(); if (x == 2) c(); } a() if b() if c() exit E = 13 N = 11 v(G) = 4
Example #10 entry i=0 void f 10(int n) { for (int i = 0 ; i < n ; i++) { a(); } } true i<n a() exit false E=5 N=5 v(G) = 2
Example #11 E = 13 N = 10 v(G) = 5
Cyclomatic Complexity for a single function/method • Cyclomatic complexity = #edges - #nodes +2 • Cyclomatic complexity = number of linearly independent paths • Cyclomatic complexity = number of decision points + 1 • Cyclomatic complexity = numbers of regions of the flow graph providing edges are not crossing each other • Be careful with simple rules such as add 1 to each if, add 1 to each switch/case, add 1 to each switch/default, et.
v(G) = Number of regions entry if a() b() if x+y exit c() d() exit
Cyclomatic Complexity Risk 1 -10 11 -20 21 -50 > 50 A simple, low risk program Moderate complexity, risk complexity Complex, high risk High risk, detestable program
- Slides: 18