Cyclomatic Complexity of switch case statement -
i'm confusing cc of switch statement
if have following code:
if (n >= 0) { switch(n) { case 0: case 1: printf("zero or one\n"); break; case 2: printf("two\n"); break; case 3: case 4: printf("three or four\n"); break; } } else { printf ("negative\n"); } what cc?
i found a post said it's 5, diagram 
(the edges 17, not 16, think it's typo)
it says need count case 0 , case 1 one
but think diagram should be: 
edges: 17,
nodes: 13,
17 - 13 + 2p = 6
i count every cases 1
my oose professor said it's 6, in different way
he said:
init => 1 if => 1 switch => 1 case 0 1 => 1 case 2 => 1 case 3 4 => 1 so should 6
what's correct answer?
i'm confused, thanks.
edited:
think it's 7. yes, 7
because if n more 5, nothing , exit switch statement.
then diagram:
now e = 18
18 - 13 + 2 = 7
am correct..?
really, really, confused...
code metric tools i've worked count each case separate branch, if it's fall through case.
but arbitrary choice. code metric tools tend err on side of caution default. way switch statement evaluated internal implementation detail vary based on type of input , number of cases (at least in c#).
the go-to answer reducing cyclomatic complexity caused switch statements convert cases/outputs dictionary. in example, code sample below. aware readability/maintainability. if switch statement long enough .net compiler automatically convert dictionary you, there no performance gain.
var outputs = new dictionary<int, string>() { { 0, "zero or one\n" }, { 1, "zero or one\n" }, { 2, "two\n" }, { 3, "three or four\n" }, { 4, "three or four\n" } }; if (n >= 0) { printf(outputs[n]); }
Comments
Post a Comment