Note that there are some explanatory texts on larger screens.

plurals
  1. POCyclomatic Complexity in piece of code with multiple exit points
    text
    copied!<p>I have this method that validates a password:</p> <pre><code>/** * 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 &lt; 8 || len &gt; 20) return false; boolean hasLetters = false; boolean hasDigits = false; for (int i=0; i&lt;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 &amp;&amp; hasLetters; } </code></pre> <p>Let's focus on the cyclomatic complexity number: what is its value?</p> <p><a href="http://metrics.sourceforge.net/" rel="nofollow">Metrics 1.3.6</a> says it's 7, but I cannot really find seven independent paths: I only find 5! And <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow">Wikipedia</a> didn't help out much&mdash;how am I suppose to use this formula <code>π - s + 2</code>?</p> <p>I have 2 <code>if</code>'s, 1 <code>for</code> and 3 exit points but I'm stuck: do I have to count the entry point? Should I count twice the first <code>if</code> since it has two conditions?</p> <p><strong>EDIT:</strong></p> <p>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?</p> <p>Well, I still cannot found the last one! I found these:</p> <ol> <li>Valid: asdf1234</li> <li>Too short: asdf123</li> <li>Too long: asdfsgihzasweruihioruldhgobaihgfuiosbhrbgtadfhsdrhuorhguozr</li> <li>Invalid character: asdf*123</li> <li>All-digit: 12345678</li> <li>No-digits: asdfghjk</li> <li>wtf???</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload