How to Read / Improve C.R.A.P Index Calculated by PHP

前端 未结 2 1045
粉色の甜心
粉色の甜心 2021-01-29 19:01

I just started working with PHPUnit and its colorful code coverage reports. I understand all the numbers and percentages save one: The C.R.A.P index. Can anyone offer me a solid

2条回答
  •  北海茫月
    2021-01-29 19:36

    @Toader Mihai offered a solid explanation. (+1 from me)

    How to lower it:

    Write less complex code OR write better tested code. (See the graph below)

    Better tested Code ?

    In this context this just means: A higher code coverage and usually results in writing more tests.

    Less complex code ?

    For example: Refactor your methods into smaller ones:

    // Complex
    function doSomething() {
        if($a) {
            if($b) {
            }
            if($c) {
            }
        } else {
            if($b) {
            }
            if($c) {
            }
        }
    }
    
    // 3 less complex functions
    function doSomething() {
        if($a) {
            doA();
        } else {
            doNotA();
        }
    }
    
    function doA() {
        if($b) {
        }
        if($c) {
        }
    }
    
    function doNotA() {
        if($b) {
        }
        if($c) {
        }
    }
    

    (just a trivial example, you'll find more resources for that i'm sure)

    Additional resources:

    First off let me provide some additional resources:

    Creators blog post about the crap index

    just in case: Cyclomatic complexity explained. Tools like PHP_CodeSniffer and PHPMD will tell you that number in case you want to know.

    And while it is for you to decide what number is "ok" one often suggested number (that is a litte high imho) is a crap index of 30 resulting in a Graph like this:

    alt text (You can get the .ods file here: https://www.dropbox.com/s/3bihb9thlp2fyg8/crap.ods?dl=1 )

提交回复
热议问题