2016-02-26 72 views
5

我有一個代碼塊,我有一個問題,減少了圈複雜度。由於需要匹配的多重條件,我不確定將其分解的最佳方式。更爲複雜的是,在其中兩種情況下創建了一個新的對象,但不是在第三種情況下(它會調用另一種方法)。這是僞代碼:環複雜度減少

if (!cond3 && !cond1 && cond2 && cond4) { 
     // actions to perform 
     calculateValues(); 
     return result; 
    } else if (!cond1 && cond2 && cond3) { 
     // actions to perform 
     Object result = new Result(); 
     return result; 
    } else if (!cond4 && cond3 && cond1 && cond5) { 
     // actions to perform 
     Object result = new Result(); 
     return result; 
    } else { 
     // throw error because inputs are invalid 
    } 
+2

對我來說很好。 –

+0

@LouisWasserman,是諷刺嗎? – jaco0646

+2

@ jaco0646,不,它不是。 –

回答

6

你應該重構代碼,使用方法,以抽象的條件下,高cyclomatic表示代碼需要重構。例如,讓我們說:如果!cond4 && cond3 && cond1 && cond5檢驗登錄的用戶都有車,那麼你應該的條件組合重構的方法:

private boolean loggedUsedHasCar() { 
    return !cond4 && cond3 && cond1 && cond5; 
} 

做同樣的事情在其他條件。有4種情況的if陳述可能很難閱讀。獲取這些語句會降低你的方法圈複雜度,使你的代碼更易讀

1

可以減少cyclometric複雜11與方程的提取公共部分作爲新的變量

boolean common = !cond1 && cond2; 
... 
if (!cond3 && common && cond4) { 
    // actions to perform 
    calculateValues(); 
    return result; 
} else if (common && cond3) { 
    // actions to perform 
    Object result = new Result(); 
    return result; 
} else if (!cond4 && cond3 && cond1 && cond5) { 
    // actions to perform 
    Object result = new Result(); 
    return result; 
} else { 
    // throw error because inputs are invalid 
}  
2

我對你的問題很感興趣,並試圖提出儘早解決與提取分離方法的條件是這樣

public class Test { 

public static void main(String[] args) { 
    cyclometricComplexityTest(); 
} 

static boolean cond1 = true; 
static boolean cond2 = true; 
static boolean cond3 = true; 
static boolean cond4 = true; 
static boolean cond5 = true; 

public static Object cyclometricComplexityTest() { 
    if (isBoolean1()) { 
     // actions to perform 
     Object result = null; 
     calculateValues(); 
     return result; 
    } else if (isBoolean2()) { 
     // actions to perform 
     Object result = new Result(); 
     return result; 
    } else if (isBoolean3()) { 
     // actions to perform 
     Object result = new Result(); 
     return result; 
    } else { 
     throw new RuntimeException(); 
    } 
} 

static boolean isBoolean1() { 
    return !cond3 && !cond1 && cond2 && cond4; 
} 

private static boolean isBoolean2() { 
    return !cond1 && cond2 && cond3; 
} 

private static boolean isBoolean3() { 
    return !cond4 && cond3 && cond1 && cond5; 
} 

static void calculateValues() {} 

static class Result {} 
} 

結果減少Cyclometric複雜性在這裏(我用MetricsReloaded IntelliJ IDEA plugin)。它真的作品通過傳播主要和輔助方法:)

enter image description here

P.S.之間的複雜性有趣的事情:我試圖提取你的條件作爲局部變量,並沒有像我最初預期的那樣降低方法的複雜性。