Search code examples
c#cyclomatic-complexity

How to reduce cyclomatic complexity on this c# method?


I'm currently doing a project for my c# classes. Our teacher gave us some code metrics limits that we have to abide to and one of them is cyclomatic complexity. Right now he complexity of the method below is 5, but it needs to be 4. Is there any way to improve that?

MethodI was talking about:

private bool MethodName()
    {
        int counter = 0;

        for (int k = 0; k < 8; k++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (class1.GetBoard()[array1[k, j, 0], array1[k, j, 1]] == player.WhichPlayer()) counter++;
            }

            if (counter == 3) return true;
            else counter = 0;
        }
        return false;
    }

Solution

  • I can wrap the conditions to reduce it. For example

    private bool MethodName()
        {
            for (int k = 0; k < 8; k++)
            {
                bool b = true;
                for (int j = 0; j < 3; j++)
                {
                    b &= class1.GetBoard()[array1[k, j, 0], array1[k, j, 1]] == player.WhichPlayer();
                }
    
                if (b) return true;
            }
            return false;
        }