具有多个出口点的代码中的循环复杂度 [英] Cyclomatic Complexity in piece of code with multiple exit points

查看:104
本文介绍了具有多个出口点的代码中的循环复杂度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种验证密码的方法:

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:


  1. 有效:asdf1234

  2. 太短:asdf123

  3. 太长:asdfsgihzasweruihioruldhgobaihgfuiosbhrbgtadfhsdrhuorhguozr

  4. 无效字符:asdf * 123

  5. 全数字:12345678

  6. 无数字:asdfghjk

  7. wtf ???

  1. Valid: asdf1234
  2. Too short: asdf123
  3. Too long: asdfsgihzasweruihioruldhgobaihgfuiosbhrbgtadfhsdrhuorhguozr
  4. Invalid character: asdf*123
  5. All-digit: 12345678
  6. No-digits: asdfghjk
  7. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆