在大型java项目中,您使用什么工具来查找未使用的/死亡的代码?我们的产品已经开发了几年,手动检测不再使用的代码变得非常困难。但是,我们会尽量删除未使用的代码。
对于一般策略/技术(而不是特定工具)的建议也很感激。
编辑:请注意,我们已经使用了代码覆盖工具(Clover, IntelliJ),但这些帮助不大。死代码仍然有单元测试,并显示为已覆盖。我想理想的工具应该是识别那些依赖于它的其他代码很少的代码集群,从而允许手动检查文档。
在大型java项目中,您使用什么工具来查找未使用的/死亡的代码?我们的产品已经开发了几年,手动检测不再使用的代码变得非常困难。但是,我们会尽量删除未使用的代码。
对于一般策略/技术(而不是特定工具)的建议也很感激。
编辑:请注意,我们已经使用了代码覆盖工具(Clover, IntelliJ),但这些帮助不大。死代码仍然有单元测试,并显示为已覆盖。我想理想的工具应该是识别那些依赖于它的其他代码很少的代码集群,从而允许手动检查文档。
当前回答
Structure101切片透视图将给出与“主”集群没有依赖关系的类或包的“孤儿”或“孤儿组”的列表(和依赖关系图)。
其他回答
我在Eclipse中对单个类所做的一件事是,将它的所有方法都更改为private,然后看看我得到了什么抱怨。对于所使用的方法,这将引起错误,我将它们返回到尽可能低的访问级别。对于未使用的方法,这将引发关于未使用方法的警告,然后可以删除这些方法。作为奖励,您经常会发现一些公共方法可以而且应该被私有。
但这是非常手工的。
我很惊讶这里竟然没有提到ProGuard。这是目前最成熟的产品之一。
ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition. Some uses of ProGuard are: Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory footprints. Making programs and libraries harder to reverse-engineer. Listing dead code, so it can be removed from the source code. Retargeting and preverifying existing class files for Java 6 or higher, to take full advantage of their faster class loading.
下面是列表死代码的示例:https://www.guardsquare.com/en/products/proguard/manual/examples#deadcode
Eclipse Goto Windows >首选项> Java >编译器>错误/警告 把它们都改成错误。修复所有错误。这是最简单的方法。这样做的好处是,您可以在编写代码时清理代码。
截图Eclipse代码:
我使用Doxygen开发了一个方法调用映射来定位从未调用过的方法。在图中,您将发现没有调用者的方法集群孤岛。这对库不起作用,因为您总是需要从一些主要入口点开始。
我会让运行中的系统保持代码使用的日志,然后开始检查几个月或几年没有使用的代码。
例如,如果您对未使用的类感兴趣,那么所有的类都可以在创建实例时记录日志。然后,一个小脚本可以将这些日志与完整的类列表进行比较,以找到未使用的类。
Of course, if you go at the method level you should keep performance in mind. For example, the methods could only log their first use. I dont know how this is best done in Java. We have done this in Smalltalk, which is a dynamic language and thus allows for code modification at runtime. We instrument all methods with a logging call and uninstall the logging code after a method has been logged for the first time, thus after some time no more performance penalties occur. Maybe a similar thing can be done in Java with static boolean flags...