testingmetricscontrol-flow-graph

Cyclomatic complexity - draw control flow graph for this java statement


Can anyone help with this?

while (x > level)
    x = x – 1;
x = 0

Solution

  • Cyclomatic complexity can be computed using the formula provided here.

    Cyclomatic complexity = E - N + P 
    where,
      E = number of edges in the flow graph.
      N = number of nodes in the flow graph.
      P = number of nodes that have exit points
    

    For your case, the graph should look like this:

    ---------------                ----------
    |  x > level  |----- NO ------>| x = x-1|
    |-------------|                ----|-----
           |      |---------------------
           |
          Yes
           |
    -------|----------
    | End while (if) |
    -------|----------
           |
           |
       ---------
       |  x = 0 |
       ----------
    

    (not an ASCII art person)

    So, the cyclomatic complexity should be:

    E = 4, N = 4, P = 2 => Complexity = 4 - 4 + 2 = 2
    

    [edit] Ira Baxter points out very well how to simplify this computation for languages like Java, C#, C++ etc. However, identifying the conditionals must be carefully performed, as shown here:

    - Start with a count of one for the method.
    - Add one for each of the following flow-related elements that are found in the method.
        Returns - Each return that isn't the last statement of a method.
        Selection - if, else, case, default.
        Loops - for, while, do-while, break, and continue.
        Operators - &&, ||, ?, and :
        Exceptions - catch, finally, throw, or throws clause.