Search code examples
javasonarqubecoding-stylecomplexity-theorycyclomatic-complexity

What is the principle behind calculating the complexity of methods?


From Sonar Metrics complexity page the following method has a complexity of 5.

public void process(Car myCar){          <- +1
        if(myCar.isNotMine()){               <- +1
             return;                         <- +1
        }
        car.paint("red");
        car.changeWheel();
        while(car.hasGazol() && car.getDriver().isNotStressed()){   <- +2
             car.drive();
        }
        return;
    }

This is how the tool calculate complexity:

Keywords incrementing the complexity: if, for, while, case, catch, throw, return (that is not the last statement of a method), &&, ||, ?

Why do case statements,if blocks and while blocks increase the complexity of the method? What is the intuition behind this metric calculation of complexity of methods?


Solution

  • It's because they have conditions in them which increase the number of tests needed to ensure that the code is correct.

    Also probably ifs have less complexity than loops (while, for). Also read up on cyclomatic complexity related to this.

    Read this blog post, it describes the actual reality of not being able to test everything and the sheer number of tests you require to test everything.