Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit and C.R.A.P index

I am using php undercontrol and the code browser report some CRAP index error on every setter/getter i.e. code like this

public function getFoo()
{
    return $this->_foo;
}

The getter/setter are covered by the unit testing, the complexity is none since there is no if/for/switch/foreach. so why I get a CRAP index of 1 for that code???

PS: self answering myself might be because the complexity is none but my main issue is that every getter/setter generate a warning because of the CRAP index so is there anyway to tell phpunit/php code coverage to make the CRAP equals to 0 for function with a 0 complexity index.

like image 1000
RageZ Avatar asked Oct 06 '11 03:10

RageZ


People also ask

What is a good crap score?

In most circles a CRAP score of 30 or below is considered acceptable, but ultimately you decide what level of complexity and what level of code coverage make sense for your team.

What is code coverage percentage?

Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.


2 Answers

The minimum CRAP score is 1, not 0. This is because the algorithm for CRAP is

CRAP(m) = comp(m)^2 * (1 – cov(m)/100)^3 + comp(m)

and the minimum cyclomatic complexity (comp) value for a function is one. So the problem is not in phpunit, but whatever is flagging a CRAP of 1 as a problem.

In general, you want to set your CRAP threshold somewhere around 5, anywhere lower and you may as well just use a simple code coverage metric (and shoot for 100%) since the complexity factor barely weighs in. A CRAP of >= 30 means that no amount of testing can make your method not crappy.

Cyclomatic complexity can generally (but there is more than one definition) be hand calculated as:

  • add 1 point for the function call
  • add 1 point for every loop
  • add 1 point for every branch
like image 52
case nelson Avatar answered Oct 23 '22 17:10

case nelson


Is it really a warning? Generally the threshold for warnings is set much higher than 1 (perhaps around 30). There is a good SO post here that shows how the number is calculated. There seems to be a few hardcoded values in my phpunit setup for CRAP of 30.

According to Alberto Savoia, the creator of the CRAP index:

"The C.R.A.P. (Change Risk Analysis and Predictions) index is designed to analyze and predict the amount of effort, pain, and time required to maintain an existing body of code."

The minimum CRAP number will be the cyclomatic complexity for code with 100% coverage. The idea being that changes to complex code are more likely to create problems than changes to simple code.

like image 38
Paul Avatar answered Oct 23 '22 17:10

Paul