开发者

Code optimization - Unused methods

开发者 https://www.devze.com 2023-02-15 04:16 出处:网络
How can I tell if a method will never be used ?开发者_如何转开发 I know that for dll files and libraries you can\'t really know if someone else (another project) will ever use the code.

How can I tell if a method will never be used ?

开发者_如何转开发

I know that for dll files and libraries you can't really know if someone else (another project) will ever use the code.

In general I assume that anything public might be used somewhere else.

But what about private methods ? Is it safe to assume that if I don't see an explicit call to that method, it won't be used ?

I assume that for private methods it's easier to decide. But is it safe to decide it ONLY for private methods ?


Depends on the language, but commonly, a name that occurs once in the program and is not public/exported is not used. There are exceptions, such as constructors and destructors, operator overloads (in C++ and Python, where the name at the point of definition does not match the name at the call site) and various other methods.

For example, in Python, to allow indexing (foo[x]) to work, you define a method __getitem__ in the class to which foo belongs. But hardly ever would you call __getitem__ explicitly.


What you need to know is the (or all possible) entry point(s) to your code:

  • For a simple command line program, this is the "main" method or, in the most simple case, the top of your script.
  • For libraries, in fact, it is everything visible from outside.
  • The situation turns more complicated if methods can be referenced from outside by means of introspection. This is language specific and requires knowledge into details of the techniques used.

What you need to do is follow all references from all entry points recursively to mark up all used methods. Whatever remains unmarked can safely - and should - be removed.

Since this is a diligent but routine piece of work, there are tools available which do that for various programming languages. Examples include ReSharper for C# or ProGuard for Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消