I have an idea for finding unused (‘dead’) methods in a large Java project but I need help deriving an implementation.
- Use AspectJ to add a ‘before’ aspect to ALL methods in project packages. The aspect will simply record (?) that the method has been executed.
- I compile a list of all classes/methods in project packages (probably using a service locator/reflection).
- The advised code is subjected to a full regression test. Ideally,
I’d like to put this into production for a while too (if a suitably
performant solution can be found). - The lists of executed methods (Step 1) and available methods (Step
2) are compared, yielding a comprehensive list of all methods that
were never called (i.e. dead code).
Since steps 2 and 4 can be conducted offline, I’m really only looking for help with Step 1.
Specifically, how can I record when a method is executed? I figure I’m going to encounter OutOfMemoryErrors pretty soon if I attempt any kind of in-memory storage. Likewise, if I store the data in a database/on the file-system, the volume of calls is likely to cause major performance issues. Has anyone ever done something similar? Any advice/suggestions appreciated.
Try checking out popular test coverage libraries like Cobertura or EMMA. They do exactly what you’re talking about and then some, though not with AspectJ. Cobertura, at least, seems to have no problem storing invocation information down to the line in memory.