How to reduce Cyclomatic complexity of Switch case statements

前端 未结 3 1069
攒了一身酷
攒了一身酷 2021-01-13 01:50

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

       string data = string.empty;
       switch (value)
        {
            case \         


        
3条回答
  •  无人及你
    2021-01-13 02:24

    Cyclomatic Complexity is one way to measure maintainability of code, and help to warn you when there's a sign you're not following good design principles. Rather than evading the error/warning you're getting from cyclomatic complexity with a solution like a dictionary lookup (which has the same maintainability problems), consider whether there's a fundamental design that should change so code like this isn't even necessary.

    Presumably the concepts encoded in your strings (e.g. "Less than 2 billion") represent a business-level decision. If that business model changes (maybe you introduce a new layer of specificity), there's some code somewhere else in your code base that will have to change to accommodate that model, right? And if that code changes, then this switch statement will also have to change in order to stay correct, right? The fact that two places in code had to change to accommodate a single Reason For Change implies that you're breaking the Single Responsibility Principle.

    One approach could be to put the data mappings you've got here into the same place. Where you might have returned "Less than 2 billion" somewhere else in your code, you can now return an object of a type which you define to hold information like this (e.g. new NumericBucket{FullText = "Less than 2 billion", AbbreviatedText = "0 - 2B"}).

    You may also consider whether these buckets should really be defined in code at all: perhaps they make more sense as configuration, so that if they need to change they can be changed instantly without requiring changes to code. In that case, the NumericBuckets could be populated based on configuration in a database or a file somewhere.

提交回复
热议问题