DBMNG数据库管理与应用

独立思考能力,对于从事科学研究或其他任何工作,都是十分必要的。
当前位置:首页 > 经验分享 > Java开发

一个Java检测无用代码的插件UCDetector

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

http://www.ucdetector.org/ 

Eclipse update site: 
http://ucdetector.sourceforge.net/update 

(1)eclipse已经提示了一些无用代码 
编译器提示: 
Preferences > Java > Compiler > Errors/Warning :Unnecessary code 
  • 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)

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


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

(2)使用UCDetector 
使用方法很简单,无论是整个项目,或者某个Java文件都可以右键选择“UCDetector/detect unnecessary code”来检测,检测后的结果显示在Problems视图里(选Group By Type)。 
 

 

 

 

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

如果想让UCDetector忽略某写代码的无用提示的话,可以在行尾添加// NO_UCD,或者使用@SuppressWarnings("ucd")。 
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号