2
votes

I am trying to use a simple pattern matching analysis to find all Factory Methods in a program? Currently, I just set some simple conditions for a method m: 1. the return type of m is not null, and also not a primary type; 2. the return statement of m gives a value which gets a new expression in this method.

Using above conditions, I could get many candidate methods for Factory Method. But obviously, the conditions are not enough. Any other condition can be added to get more accurate factory methods.

Thanks.

2

2 Answers

3
votes

This sounds like an impossible task to me. For example, even your current criteria are incorrect, IMHO. A factory method returns an instance of some class, but

  • it does not necessary create the instance (it might use a cache, as Integer.valueOf does, for example),
  • it might create an instance using something other than the new operator
  • it might delegate to another method or another class to create the instance

You could search for commonly used names like "createXxx", "newXxx" or "valueOf", but this would of course return potential factory methods, and would miss many.

The factory pattern is just a pattern. It's not something so rigid that you can identify it automatically, IMHO.

1
votes

I think this can't be done, because doing so would include solving the halting problem. Restricting yourself to pattern-matching (on Strings, I assume) only makes it harder.