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

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

问题描述

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

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?

Metrics 1.3.6 说是 7,但我真的找不到 7 个独立路径:我只找到 5!而 Wikipedia 并没有多大帮助—我想如何使用这个公式 π-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 个 if、1 个 for 和 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?

好的,现在我发现圈数是 7.这意味着有 7 个独立的路径,所以如果我想覆盖 100% 的代码,我应该能够找到 7 个不同的测试用例,对吗?

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???

推荐答案

我认为诀窍是逻辑运算符被计算在内.

I think the trick is that the logical operators are counted.

基于您在 McCabe 下的 Metrics 链接 (http://metrics.sourceforge.net/)圈复杂度部分:

Based off of your Metrics link (http://metrics.sourceforge.net/) under the McCabe Cyclomatic Complexity section:

1 初始流程

3 个决策点(如果、为、如果)

3 decision points (if,for,if)

3 个条件逻辑运算符 (||,||,||)

3 conditional logic operators (||,||,||)

总数:7

这篇关于具有多个退出点的代码段中的圈复杂度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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