Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

Maybe it is based on the Cyclomatic Complexity by McCabe (at least looks like it).
This metric is widely used in the Software Engineering field.
Take a look at this: http://en.wikipedia.org/wiki/Cyclomatic_complexity

Somar measures cyclomatic complexity, which represents the number of linearly independent paths through the source code.

The key to answering your question comes from a research paper of Thomas McCabe, published in December of 1976:

It can be shown that the cyclomatic complexity of any structured program with only one entrance point and one exit point is equal to the number of decision points (i.e., 'if' statements or conditional loops) contained in that program plus one.

This is precisely what Sonar does: it finds the decision points, which come from loops, conditional statements, and multipart boolean expressions, and counts their number.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top