sRiRaJ mISHrA
sRiRaJ mISHrA

Reputation: 96

Cyclomatic Compleity IF ELSE vs SWITCH CASE

Many code analysis tools like sonar throw errors for switch case if used instead of multiple is-else for cyclomatic complexity . Is there a number which should be a threshold of when one should use if else and when one should use switch case ? Say if its a case of 50 , to reduce cyclomatic complexity one should use switch case ? Would be good if you could support your answer with an example ?

Upvotes: 1

Views: 3679

Answers (1)

John
John

Reputation: 5297

To answer the question with another question.

Would you rather read:

if(cond1)..

else if(cond2)...

else if(cond50)...

else ...

or

value = map.get(key)

If there are so many possible cases, than neither the switch or if seem appropriate and should therefore be replaced with key-value structure or state machine pattern - if branching is really complicated.

You can find an example implementation here:

fsm

As to when to use if or switch, keep in mind that switch cannot accept the following types:

long, double, float, boolean so when you have such an input, switch is obviously not a choice.

I wouldn't use number as a metric to use switch or if statement. There is one exception however, if an input can have only 2 possible values it is better to use if. Even Sonar should suggest you this.

That said, switch is usually more readable than the series of if statements. As an important decision factor, other than readability, within switch statement there can be groups of values which might require same execution path. It is basically safer version of the goto. Unlike if, where each outcome is usually bound to specific execution path.

Upvotes: 2

Related Questions