Explain Codes LogoExplain Codes Logo

How to find unused/dead code in java projects

java
best-practices
tools
performance
Nikita BarsukovbyNikita Barsukov·Feb 17, 2025
TLDR

To identify dead code quickly, use robust tools like SonarQube:

mvn sonar:sonar -Dsonar.host.url=http://your_sonar_host

SonarQube scans your Java projects to highlight unused code under Code Smells, providing an actionable solution that's easy to implement with minimal setup.

Additionally, consider employing CodePro AnalytiX plugin in Eclipse. It identifies unused methods and offers insightful optimization recommendations.

Tools that enhance efficiency

Optimizing logs for better performance

Avoid getting caught in a cobweb of excessively logged methods. Boost performance by embracing selective tracking. Only record the initial usage of methods, using scripts and static boolean flags to limit logging to necessary instances, trimming the time easily.

static boolean firstCall = true; void logIfFirstCall() { if (firstCall) { System.out.println("Hey, you called me first! // Surely, I'm not a 'phantom method'! 🙃 "); firstCall = false; } }

Dynamically modify code

Gather the advantages of logging without facing performance degradation. Dynamic code modification inserts logging commands on-the-fly and disables them after usage validation.

Don't neglect manual review

Automated tools might dish out false positives or miss subtle intricacies. Scripts spotting code clusters with few dependencies help humans to step in, conducting a more detailed review process.

Bringing in alternatives

Implementing Continuous Integration (CI) tools

Integrating static analysis tools into your CI framework such as Jenkins or GitHub Actions ensures a thorough analysis of every commit or pull request before they merge.

Custom scripts for unique needs

Project-specific characteristics often call for custom scripts. Tap into abstract syntax tree parsing or bytecode analysis techniques to create custom detection for unused code.

Steps to strengthen human review

Harness the power of collective interpretation

Peer code reviews are an invaluable tool. They facilitate the identification of redundant methods and assist in recognizing outdated and obsolete classes.

Manual searches with experienced developers

Leverage senior developers' intuitions to root out unused code; after all, they've been exploring this haunted mansion for quite a while now!

Reliable documentation and strict coding standards

Maintain clear documentation and adhere to stringent coding standards to keep the code self-explanatory, with outliers potentially indicating their candidate status for removal.