What is the best way to remove dead code from your application? [closed]

拜拜、爱过 提交于 2019-12-11 05:24:02

问题


I often feel that after iterating over my code for a number of times I am left with functions or classes or other lines of code in general which made sense in the previous revision but are not very useful for the new revision. I know that a profiler can tell you what part of your code was called when you run your test cases? But how does one go about identifying what part of the code never got called to remove it so that whats left is more readable? For example, is there a quick way to know which functions in your code are not being called from anywhere and can be safely removed. It may sound like a trivial question for a small code base, but when your code base grows over the years, this becomes an important and not so trivial question.

To summarize the question, for different languages, what is the best approach to remove dead code? Are there any lanaguage agnostic solutions or strategies for this. Or does each language provide a tool for identifying dead code.

We normally program in Java or Python or Objective-C.


回答1:


The term you're looking for is "code coverage" and there are various tools that will generate that information. You would have to make sure that you exercise every possible path through your code in order to be able to detect "dead code" with such a tool though, which is only possible with a really extensive set of tests.

Most compilers have some level of dead code detection, but that only detects code that cannot possibly be called, not code that will never be called due to program logic, etc..

edit:

for Python specifically: How can you find unused functions in Python code?

for Java: How to find unused/dead code in java projects, Java: Dead code elimination

for Objective-C: Xcode -- finding dead methods in a project, Cleaning up Objective-C code




回答2:


For functions, try a global search on the function name, and analyze what you get. Dead code inside a function will usually be findable.

If you suspect a function of being unused, you can remove it, or comment it out, and see if what you've got still compiles.

This only works on functions that are unused because they are no longer called. Functionality that is never used because the control path through the code is no longer active is harder to find, and code analysis tools won't do well at finding it either.




回答3:


You can use the code coverage report to find out the function which are not used or part of function which is never executed.

Based on the logic, you can treat them as dead code/unused code.

Popular code coverage tools that can be used:

  • C/C++: gcov & lcov
  • Python: Coverage.py
  • Java: JCov
  • Objective-C: xccov


来源:https://stackoverflow.com/questions/5570774/what-is-the-best-way-to-remove-dead-code-from-your-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!