1

Cyclomatic complexity is number of test cases that are necessary to achieve thorough test coverage of a particular module.

Consider the following pseudo-code :

If (A > B) and (C > D) then
    A = A + 1
    B = B + 1
Endif

I think only two test cases are required here, one for true condition another for false condition, so cyclomatic complexity should be 2 but answer is 3(not sure why).

Someone please help me understand why the answer is 3 instead of 2.

keenthinker
  • 7,645
  • 2
  • 35
  • 45
  • 2
    This question appears to be off-topic because it is about computer science, for which there are other sites. – bmargulies Jul 21 '13 at 11:29

2 Answers2

2

Cyclomatic complexity directly measures the number of linearly independent paths through a program's source code.

If (A > B) and (C > D) then
    A = A + 1
    B = B + 1
Endif

Case 1.

If (true) and (true) then
    // Execute some code
Endif

Case 2.

If (true) and (false) then
    // Don't execute code
Endif

Case 3.

If (false) and (2nd part won't be executed) then
    // Don't execute code
Endif

So Cyclomatic complexity will be 3.

surender8388
  • 474
  • 3
  • 12
1

The code will be translated by compilers to something like the following pseudo-assemley code:

A - B
branch if greater then 0 to end
C - D
branch if greater then 0 to end
inc A
inc B
end:
...

Now, in order to make all possible choices in all branches, you need 3 test cases:

  1. A <= B (branch in first branch instruction)
  2. C <= D (branch in second branch instruction)
  3. A > B and C > D (don't branch in 2nd branch instruction and get to the increasing instructions)

Note that for alternative definition of "coverage" - "All instructions coverage", 1 test case can be enough (with the above compiled code), because even if you don't branch, the "branch if.." instruction is still executed, so for A>B and C>D test case, you actually go through all instructions.


P.S. assuming here:

Cyclomatic complexity is number of test cases that are necessary to achieve thorough test coverage of a particular module.

amit
  • 175,853
  • 27
  • 231
  • 333
  • The author is specifically asking about "Cyclomatic complexity". – simonzack Jul 21 '13 at 11:30
  • @simonzack: `Cyclomatic complexity is number of test cases that are necessary to achieve thorough test coverage of a particular module.` The answer aims to show that you need 3 test cases to cover the module. Now, what "cover" is may be various, I assumed here "all branches coverage". – amit Jul 21 '13 at 11:32