phprefactoringcode-coveragelegacy-code

Dead code detection in PHP


I have a project with very messy code - lots of duplication and dead code here and there.

Some time ago there was zero code coverage by unit-tests but now we're trying to write all new code in T.D.D. manner and lowering technical debt by covering "old" code by unit-tests as well(test-last technique).

Business logic's complexity is quite high and sometimes no one can answer whether some methods are used or not.

How this dead code methods can be found? Extensive logging? Higher test coverage?(It is not very easy because customers want new features to come out)


Solution

  • xdebug's code coverage tools allow you to test which lines of code are actually being executed, without needing to put trace statements in all of the functions/methods.

    Example:

    <?php
        xdebug_start_code_coverage();
    
        function a($a) {
            echo $a * 2.5;
        }
    
        function b($count) {
            for ($i = 0; $i < $count; $i++) {
                a($i + 0.17);
            }
        }
    
        b(6);
        b(10);
    
        var_dump(xdebug_get_code_coverage());  // array '/path/file.php' => array line_number => int 1 or 0.
    ?>