Is there a tool for finding unreferenced functions

2019-01-07 09:54发布

I want to delete foo() if foo() isn't called from anywhere.

7条回答
聊天终结者
2楼-- · 2019-01-07 09:59

Bear in mind that Resharper (and probably other similar tools as well) will not highlight unused methods if the methods are marked public. There is no way a static code analysis tool will be able to check whether the methods of your assembly are used by other assemblies outside your solution. So the first step in weeding out unused methods is to reduce their visibility to private or internal.

查看更多
Luminary・发光体
3楼-- · 2019-01-07 09:59

Resharper does this, and not just with methods. It also does it with using statements, variables etcetera.

查看更多
我命由我不由天
4楼-- · 2019-01-07 10:09

Well, if VS doesn't do this natively, a simple method is to right click on the method and select "find all references" . If there is only 1 reference (where it is declared) it most likely isn't used anywhere else.

查看更多
甜甜的少女心
5楼-- · 2019-01-07 10:12

NDepend will also report on potentially unused code.

查看更多
趁早两清
6楼-- · 2019-01-07 10:17

Yes, the MZ-Tools addin has a review dead code feature.

查看更多
叛逆
7楼-- · 2019-01-07 10:19

The tool NDepend can help find unused code in a .NET code base. Disclaimer: I am one of the developer of this tool.

NDepend proposes to write Code Rule over LINQ Query (CQLinq). Around 200 default code rules are proposed, 3 of them being dedicated to unused/dead code detection:

NDepend is integrated in Visual Studio, thus these rules can be checked/browsed/edited right inside the IDE. The tool can also be integrated into your CI process and it can build reports that will show rules violated and culprit code elements.

If you click these 3 links toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used only by unused dead types and methods (recursive).

This is static analysis, hence the prefix Potentially in the rule names. If a code element is used only through reflection, these rules might consider it as unused which is not the case.

In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually unused/dead code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.

查看更多
登录 后发表回答