2016-03-11 37 views

回答

1

環複雜度可以使用提供的公式here來計算。

Cyclomatic complexity = E - N + P 
where, 
    E = number of edges in the flow graph. 
    N = number of nodes in the flow graph. 
    P = number of nodes that have exit points 

對於你的情況,該圖應該是這樣的:

---------------    ---------- 
| x > level |----- NO ------>| x = x-1| 
|-------------|    ----|----- 
     |  |--------------------- 
     | 
     Yes 
     | 
-------|---------- 
| End while (if) | 
-------|---------- 
     | 
     | 
    --------- 
    | x = 0 | 
    ---------- 

(非ASCII藝術人)

因此,cyclomatic complexity應該是:

E = 4, N = 4, P = 2 => Complexity = 4 - 4 + 2 = 2 

[編輯] Ira Baxter指出很好如何簡化這種計算的語言,如JavaC#C++等。然而,識別條件語句必須小心,如圖所示here

- Start with a count of one for the method. 
- Add one for each of the following flow-related elements that are found in the method. 
    Returns - Each return that isn't the last statement of a method. 
    Selection - if, else, case, default. 
    Loops - for, while, do-while, break, and continue. 
    Operators - &&, ||, ?, and : 
    Exceptions - catch, finally, throw, or throws clause. 
+1

而對於像Java結構語言,你可以計算它作爲#條件加1.(1 + 1 ==> 2爲這個例子)。 –

+0

考慮到休息和繼續總是伴隨着一個條件(否則循環立即退出),你不會只計算條件? – nonconvergent

+0

@nonconvergent - 我想'如果'+'break'算作一個,而不是兩個。如果我在OP中重寫while while(true).. if(x> = level)break',根據規則我會得到+2('if'和'break')。我的感覺是'if .. break'和虛擬'while''應該是例外,因爲複雜性似乎是相同的。無論如何,我不太清楚這對於Programmers.SE來說是個好問題。 – Alexei