2016-02-26 73 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.之间的复杂性有趣的事情:我试图提取你的条件作为局部变量,并没有像我最初预期的那样降低方法的复杂性。