Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce Cyclomatic complexity of Switch case statements

Tags:

c#

There is an function which has switch case and we need to reduce its CC

       string data = string.empty;
       switch (value)
        {
            case "Less than 2 billion":
                data = "0 - 2B";
                break;
            case "2 billion to 10 billion":
                data = "2B - 10B";
                break;
            case "10 billion to 20 billion":
                data = "10B - 20B";
                break;
            case "20 billion to 50 billion":
                data = "20B - 50B";
                break;
            case "Greater than 50 billion":
                data = "> 50B";
                break;
            case "N/A":
                data = "N/A";
                break;
            case "[items] > 0":
                data = string.Empty;
                break;
        }
        return data;
like image 469
Jeevan Bhatt Avatar asked Oct 14 '11 05:10

Jeevan Bhatt


People also ask

How can cyclomatic complexity be reduced in a switch case?

Avoid use of switch/case statements in your code. Use Factory or Strategy design patterns instead. Complexity of 8 (1 for each CASE and 1 for method itself). Refactoring using Factory design pattern and complexity changed to 1.

What is the complexity of a switch statement?

It is at worst O(n). Sometimes (and this is language and compiler dependent), it translates to a jump table lookup (for "nice" switches that don't have too large a case range). Then that is O(1).


1 Answers

You could use a dictionary lookup in this case, it would be a little less code and clearer.

like image 169
Ben Voigt Avatar answered Sep 19 '22 01:09

Ben Voigt