How to improve Cyclomatic Complexity?

后端 未结 4 1358
野性不改
野性不改 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 14:00

    Case 1 - deal with this simply by refactoring into smaller functions. E.g. the following snippet could be a function:

    objectC = doThatMethod();
    if(objectC != null)
    {
     doXXX();
    }
    else{
     doYYY();
    }
    

    Case 2 - exactly the same approach. Take the contents of the else clause out into a smaller helper function

    Case 3 - make a list of the strings you want to check against, and make a small helper function that compares a string against many options (could be simplified further with linq)

    var stringConstants = new string[] { StringConstants.AAA, StringConstants.BBB etc };
    if(stringConstants.Any((s) => e.PropertyName.Equals(s))
    {
        ...
    }
    

提交回复
热议问题