Java检测无用代码之UCDetector

如果你的项目代码量很大,或者维护了好多年,就必然会存在很多无用代码,维护这些代码会带来很大的成本开支,有时候需要清理这些无用代码,可以通过代码覆盖率工具来检测,但是这样也会很费事。UCDetector : Unnecessary Code Detector,一个检测无用的public代码(类、方法,属性等)的eclipse插件。

[url=http://www.ucdetector.org/]http://www.ucdetector.org/[/url]

Eclipse update site:
[url=http://ucdetector.sourceforge.net/update]http://ucdetector.sourceforge.net/update[/url]

[b](1)eclipse已经提示了一些无用代码[/b]
编译器提示:
Preferences > Java > Compiler > Errors/Warning :Unnecessary code
[list][*]Value of local variable is not used
[*]Value of parameter is not used(默认Ignore)
[*]Unused type parameter(默认Ignore)
[*]Unused import
[*]Unused private member
[*]Unnecessary 'else' statement(默认Ignore)
[*]Unnecessary cast or 'instanceof' operation(默认Ignore)
[*]Unnecessary declaration of thrown exception(默认Ignore)
[*]Unused 'break' or 'continue' label
[*]Redundant super interface(默认Ignore)[/list]

代码辅助提示:
Preferences > Java > Code Style > Clean Up :Unnecessary Code
[list]
[*]Unused code
[*] Remove unused imports
[*] Remove unused private memebers(默认未选中)
[*] Remove unused local variables(默认未选中)
[*]Unnecessary Code
[*] Remove unnecessary casts
[*] Remove unnecessary '$NON-NLS$' tags
[/list]

看开源代码的时候经常会看到类似//$NON-NLS-1$、//$NON-NLS-2$......//$NON-NLS-n$等这样的注释。意思当前行的第n个字符串不需要外置做国际化,其中NLS代表"National Language Support"。eclipse有一个resources creator tool,能够将代码中的字符串,自动提取到.properties中去。在java代码中点击右键,Source > Externalize Strings。

[b](2)使用UCDetector [/b]
使用方法很简单,无论是整个项目,或者某个Java文件都可以右键选择“UCDetector/detect unnecessary code”来检测,检测后的结果显示在Problems视图里(选Group By Type)。
[img]http://dl2.iteye.com/upload/attachment/0093/6480/a4cadc87-69d1-357c-a248-b31b5c47512f.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0093/6482/f18ab74f-5017-3425-9374-d47ba40fc435.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0093/6511/d13484b9-8b9d-3fba-a0c4-f2c73f8a26d8.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0093/6513/c4db110b-82b4-31e8-9314-e8e9aae2609d.png[/img]

工具再智能也只是帮助你检测出来那些没有被引用的代码,但是是否真的这些代码无用,还需要按照实际情况确认。比如,虽然没有直接调用的但却只用于反射的、类似于Spring的外部依赖注入的、提供给第三方的API、其他Jar中调用的,.....等等。

如果想让UCDetector忽略某写代码的无用提示的话,可以在行尾添加// NO_UCD,或者使用@SuppressWarnings("ucd")。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值