2

I'm trying to calculate the NPath Complexity within a function, but I'm unsure what parts I count.

My understanding is that it'll sum:

  • If
  • Else
  • Else If
  • Switch
  • Case
  • Default
  • Do
  • While

Is this correct? Or am I missing something?

James
  • 121

2 Answers2

2

You also need to include operators such as && || and ? :, since these themselves can produce alternate execution paths.

robert
  • 121
  • You also left for out of your list of control-flow statements ... – robert Sep 03 '14 at 12:43
  • actually take a look here http://www.leepoint.net/notes-java/principles_and_practices/complexity/complexity-java-method.html the term is "cyclomatic complexity", there's actually a few other things I forgot, such as try/catch/finally... – robert Sep 03 '14 at 12:51
  • npath and cyclomatic are different types of complexity and are measured differently. –  Sep 03 '14 at 14:06
  • Okay, I looked this up. Seems N-path takes into account the possible outcome of all operations, but OP only mentions flow-control. Do you think he meant CC? – robert Sep 03 '14 at 14:33
  • Its possible... though it probably needs more clarification to determine exactly what the OP is after. –  Sep 03 '14 at 14:43
  • I just want to know what's included in NPath Complexity :) – James Sep 05 '14 at 15:29
  • well, I think the short answer is everything, but I think it comes down to the number of possible outcomes for a function. This article gives a basic summary: http://codingswag.ghost.io/cyclomatic-and-npath-complexity-explained/ – robert Sep 05 '14 at 15:39
1

The NPath Complexity is the sum of the possible routes through your code (ignoring cycles).

The complexity therefore depends on the structure of your code rather than just the tokens:

if (x) {
   if (y) {
     // Do something
   } else {
    // Do something else
   }
} else {
  // Do something even more else
}

Has 3 possible paths that could be taken, depending on the values of x and y.

As you nest control structures more deeply, the number of possible paths increases exponentially.

Skimming this code: http://pmd.sourceforge.net/pmd-4.3/xref/net/sourceforge/pmd/rules/design/NpathComplexity.html will give an idea of the complexity of calculating the complexity:-)

MZB
  • 545