具有多个出口点的代码中的循环复杂度 [英] Cyclomatic Complexity in piece of code with multiple exit points
问题描述
我有这种验证密码的方法:
I have this method that validates a password:
/**
* Checks if the given password is valid.
*
* @param password The password to validate.
* @return {@code true} if the password is valid, {@code false} otherwise.
*/
public static boolean validatePassword(String password) {
int len = password.length();
if (len < 8 || len > 20)
return false;
boolean hasLetters = false;
boolean hasDigits = false;
for (int i=0; i<len; i++) {
if (!Character.isLetterOrDigit(password.charAt(i)))
return false;
hasDigits = hasDigits || Character.isDigit(password.charAt(i));
hasLetters = hasLetters || Character.isLetter(password.charAt(i));
}
return hasDigits && hasLetters;
}
让我们关注圈复杂度数:它的值是什么?
Let's focus on the cyclomatic complexity number: what is its value?
指标1.3.6 表示现在是7,但我不能找到七个独立的路径:我只有五个!而且维基百科并没有多大帮助-我想怎么使用这个公式π-s + 2
?
Metrics 1.3.6 says it's 7, but I cannot really find seven independent paths: I only find 5! And Wikipedia didn't help out much—how am I suppose to use this formula π - s + 2
?
如果有,我有2个, 1个
和3个出口点,但我被卡住了:我必须计算入口点吗?我应该对第一个 if
进行两次计数,因为它有两个条件吗?
I have 2 if
's, 1 for
and 3 exit points but I'm stuck: do I have to count the entry point? Should I count twice the first if
since it has two conditions?
编辑:
好,现在我发现Cyclomatic Number是7。这意味着有7条独立的路径,因此如果我愿意,我应该能够找到7个不同的测试用例覆盖100%的代码,对吗?
Ok, now I found out that Cyclomatic Number is 7. This means that there are 7 independent paths and so I should be able to find 7 different test cases if I would to cover 100% of code, am I right?
嗯,我仍然找不到最后一个!
我找到了这些:
Well, I still cannot found the last one! I found these:
- 有效:asdf1234
- 太短:asdf123
- 太长:asdfsgihzasweruihioruldhgobaihgfuiosbhrbgtadfhsdrhuorhguozr
- 无效字符:asdf * 123
- 全数字:12345678
- 无数字:asdfghjk
- wtf ???
- Valid: asdf1234
- Too short: asdf123
- Too long: asdfsgihzasweruihioruldhgobaihgfuiosbhrbgtadfhsdrhuorhguozr
- Invalid character: asdf*123
- All-digit: 12345678
- No-digits: asdfghjk
- wtf???
推荐答案
我认为,诀窍在于计算逻辑运算符。
I think the trick is that the logical operators are counted.
基于您的Metrics链接( http://metrics.sourceforge.net/ )在 McCabe圈复杂度部分下:
Based off of your Metrics link (http://metrics.sourceforge.net/) under the McCabe Cyclomatic Complexity section:
1初始流
3个决策点(if,for,if)
3 decision points (if,for,if)
3个条件逻辑运算符(||,|| ,, ||)
3 conditional logic operators (||,||,||)
总计:7
这篇关于具有多个出口点的代码中的循环复杂度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!