vmutius's avatar

Track dead unsued code

As you are working on a project you create a lot of files. Some will be used in your application, some not anymore. How do you track old, unused code?

0 likes
3 replies
LaryAI's avatar
Level 58

Tracking and identifying unused code in a project can be challenging, but there are several strategies and tools you can use to help manage this:

  1. Static Code Analysis Tools: These tools can analyze your codebase and identify potentially unused code. Some popular tools include:

    • PHPStan or Psalm for PHP projects.
    • ESLint for JavaScript projects, which can be configured to detect unused variables and functions.
    • SonarQube for a more comprehensive analysis across multiple languages.
  2. Code Coverage Tools: Running tests with code coverage can help identify which parts of your code are not being executed. This can give you a clue about potentially unused code. Tools include:

    • Xdebug with PHPUnit for PHP.
    • Istanbul for JavaScript.
  3. Dependency Analysis: Tools like Deptrac for PHP can help you understand the dependencies in your project and identify unused classes or files.

  4. Manual Code Review: Regularly reviewing your codebase can help you spot unused code. This is often more effective when combined with the above tools.

  5. Version Control: Use your version control system (like Git) to track changes and identify when certain files or functions were last modified. This can help you determine if they are still in use.

  6. Automated Scripts: Write custom scripts to search for unused files or functions. For example, you can write a script to find PHP files that are not included or required anywhere in your project.

Here's a simple example of how you might use a script to find unused PHP files:

#!/bin/bash

# Find all PHP files in the project
find . -name "*.php" > all_php_files.txt

# Find all PHP files that are included or required
grep -r -E "include|require" . | awk -F: '{print $2}' | sed 's/.*[\"\']//;s/[\"\'].*//' > used_php_files.txt

# Compare the two lists to find unused files
comm -23 <(sort all_php_files.txt) <(sort used_php_files.txt) > unused_php_files.txt

echo "Unused PHP files:"
cat unused_php_files.txt

This script is a basic example and may need adjustments based on your project's structure and complexity.

By combining these methods, you can effectively track and manage unused code in your projects.

1 like
s4muel's avatar

there is a concept of "tombstones", where you basically mark every class/method/whatever with a tombstone (a "pin to log that marked piece of code executed"), then run your application for a period of time and then evaluate which tombstones were called.

a quick search (not tried) resulted in this package which looks promising: https://github.com/scheb/tombstone and he explains the concept a but deeper than my one sentence answer;)

1 like

Please or to participate in this conversation.