How to reduce Cyclomatic complexity of case switch statements

There is a function that has a switch enclosure, 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;
+5
source share
3 answers

In this case, you can use the dictionary search, it will be a little less code and more understandable.

+8
source

You can do something like this

private Dictionary<EnumType, Action<param1Type,param2Type,etc> strategies = 
new Dictionary<EnumType, Action<param1Type, param2Type, etc>();

...

private void LoadDictionary()
{
strategies.Add(enumType.Option1, Method1);
strategies.Add(enumType.Option2, Method2);
...
}

...

private void Method1(param1Type param, param2Type param2, etc)
{
// your specific logic here
}

And you use it as follows:

public void DoSomethingDependingOnCase(enumType option, param1Type param1, param2Type param2)
{
strategies[option].Invoke(param1,param2,etc);
}
+2
source

- , , . , /, , , ( ), , , , .

, (, "Less than 2 billion"), -. - ( , ), - - , , , ? , switch , , ? , , , , .

, . "Less than 2 billion" - , , (, new NumericBucket{FullText = "Less than 2 billion", AbbreviatedText = "0 - 2B"}).

, : , , , , , . NumericBucket - .

0

All Articles