What is the best way to remove dead code from your

2019-07-01 10:58发布

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.

2条回答
做自己的国王
2楼-- · 2019-07-01 11:24

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

查看更多
贼婆χ
3楼-- · 2019-07-01 11:32

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.

查看更多
登录 后发表回答