在大型java项目中,您使用什么工具来查找未使用的/死亡的代码?我们的产品已经开发了几年,手动检测不再使用的代码变得非常困难。但是,我们会尽量删除未使用的代码。

对于一般策略/技术(而不是特定工具)的建议也很感激。

编辑:请注意,我们已经使用了代码覆盖工具(Clover, IntelliJ),但这些帮助不大。死代码仍然有单元测试,并显示为已覆盖。我想理想的工具应该是识别那些依赖于它的其他代码很少的代码集群,从而允许手动检查文档。


当前回答

有一个Java项目-死代码检测器(DCD)。对于源代码,它似乎工作得不太好,但对于.jar文件-它真的很好。另外,您可以通过类和方法进行过滤。

其他回答

代码覆盖工具,如Emma、Cobertura和Clover,将检测您的代码,并记录通过运行一组测试调用代码的哪些部分。这是非常有用的,并且应该是开发过程中不可分割的一部分。它将帮助您确定测试套件对代码的覆盖程度。

然而,这与识别真正的死代码是不同的。它只识别被测试覆盖(或未被测试覆盖)的代码。这可能会给您带来假阳性(如果您的测试没有覆盖所有场景)和假阴性(如果您的测试访问了实际上从未在真实场景中使用过的代码)。

我认为真正识别死代码的最好方法是在实时运行的环境中使用覆盖工具,并在一段较长的时间内分析代码覆盖率。

If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.

我个人从来没有见过这样做,也不知道如何使用上述工具来检测和分析没有通过测试套件调用的代码——但我相信它们可以做到。

Eclipse可以显示/突出显示无法访问的代码。JUnit可以向您显示代码覆盖率,但是您需要进行一些测试,并且必须决定是否缺少相关的测试,或者代码确实没有使用过。

我很惊讶这里竟然没有提到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

有一些工具可以分析代码并提供代码覆盖率数据。这可以让您看到(当代码运行时)调用了多少代码。您可以使用任何这些工具来找出您有多少孤立代码。

理论上,您无法确定地找到未使用的代码。这有一个数学证明(好吧,这是一个更普遍的定理的特殊情况)。如果你很好奇,可以查一下《停止问题》。

这可以在Java代码中以多种方式表现出来:

根据用户输入、配置文件、数据库条目等加载类; 加载外部代码; 将对象树传递给第三方库; 等。

也就是说,我使用IDEA IntelliJ作为我的IDE选择,它有广泛的分析工具,可以发现模块、未使用的方法、未使用的成员、未使用的类等之间的依赖关系。它也很智能,就像一个没有被调用的私有方法被标记为未使用,但一个公共方法需要更广泛的分析。