1

Say I have a controller

public function someAction(){
    $something = Helper::something();
}

And I have a test to check Helper::something()returns/does whatever it should.

Down the line I refactor someAction() to not need that method anymore (and for arguments sake it's not used elsewhere). When I run tests/coverage, Helper::something() will show up as covered/used code, despite it only ever being used in a test.

Are there any techniques to tell if the code/method is actually used?

I'm not wondering how long it would take to find dead code, just wondering if there are any techniques, tools etc to help identify it automatically.

  • 1
    Possible duplicate of Effective way to estimate dead code removal? – gnat Aug 23 '19 at 13:34
  • 1
    @gnat I don't think that's a duplicate. This is not asking for how to determine how much time or effort it will take to remove dead code, but methods for finding dead code. – Thomas Owens Aug 23 '19 at 14:05
  • Maybe you shouldn't be testing Helper::something(). Maybe you should be testing someAction(). – Brandon Aug 23 '19 at 17:13
  • @Brandon ideally you should be testing both :P – Kevin Van Dyck Sep 6 '19 at 14:54
5

It depends on your language and framework.

Your test coverage tools are doing the right thing. When you examine test coverage, you want to see what lines of code are executed by tests. Using test coverage to find dead code isn't necessarily the best, especially at the unit and integration test level, since you may be exercising code paths that are never truly used in a deployed system.

There are a few ways to find dead code:

  • Static analysis tools may find dead code. However, in languages that allow methods to be called dynamically, this may have false positives. In addition, public methods may be called outside of the specific application and may also show up as unused code because they are unused in the context of your application.
  • Dynamic analysis tools can track the running application. If you allow the tracking to occur over a long enough period of time and at a large enough sample rate, you can increase confidence in finding the lines of code that are used. However, you may not detect code that is used, but is used very infrequently, resulting in false positives.
  • Code reading. Simple searching of instances where classes are instantiated and methods are called. Some IDEs for some languages offer some level of static analysis capabilities (see the first point) to find uses of code. Again, you won't detect callers that live in other applications and may miss dynamic calls, but that always tends to be a risk.
  • Thanks! I'll take a look into those ideas. – TMH Aug 23 '19 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.