How to improve Cyclomatic Complexity?

后端 未结 4 1359
野性不改
野性不改 2021-02-13 13:31

Cyclomatic Complexity will be high for methods with a high number of decision statements including if/while/for statements. So how do we improve on it?

I am handling a

4条回答
  •  感动是毒
    2021-02-13 13:54

    I'm not a C# programmer, but I will take a stab at it.

    In the first case I would say that the objects should not be null in the first place. If this is unavoidable (it is usually avoidable) then I would use the early return pattern:

    if ( objectA == NULL ) {
        return;
    }
    // rest of code here
    

    The second case is obviously not realistic code, but I would at least rather say:

    if ( isTrue && e > 1 ) {
        DoStuff();
    }
    

    rather than use two separate ifs.

    And in the last case, I would store the strings to be tested in an array/vector/map and use that containers methods to do the search.

    And finally, although using cyclomatic complexity is "a good thing" (tm) and I use it myself, there are some functions which naturally have to be a bit complicated - validating user input is an example. I often wish that the CC tool I use (Source Monitor at http://www.campwoodsw.com - free and very good) supported a white-list of functions that I know must be complex and which I don't want it to flag.

提交回复
热议问题