Java – Cyclomatic Complexity in piece of code with multiple exit points

complexity-theorycyclomatic-complexityjavareturn

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

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?

EDIT:

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

Best Answer

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

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

1 Initial flow

3 decision points (if,for,if)

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

total: 7