I recently worked on a public API, and I was tormented by choosing static factory methods and a constructor. Static factory methods definitely make sense in some cases, but in other cases this is not so clear, and I'm not sure if consistency with the rest of the API is reason enough to include them in constructors.
In any case, I came across a quote from an interview with Bill-Venners with Josh Bloch , which I found useful:
When you write a class, you can run my list of books on the benefits of static plants over public designers. If you find that a significant number of such advantages in the case, you should go with static factories. Otherwise, you should go to the constructors.
Some people were disappointed to find this advice in my book. They read it and said: "You argued so much for public static plants that we should use them by default." I The only real flaw in this means that it is a little embarrassing to people who are used to using constructors to create their objects. And I suppose this provides a bit less visual hint to the program. (You do not see a new keyword.) And it is a little more difficult to find static factories in the documentation, because Javadoc groups all the constructors together. But I would say that everyone should consider static time plants and use them when they are needed.
After reading this quote and the study that Uri * mentioned , I tend to err in favor of designers, unless there is a compelling reason to do otherwise. I think a static factory method without a good reason is probably just unnecessary complexity and over engineering. Although I could change my mind again tomorrow ...
* Unfortunately, this study focused less on static factory methods and more on the factory pattern (where there is a separate factory object for creating new instances), so I'm not sure that it can really be concluded that static factory methods confuse many programmers. Although the study gave me the impression that they often will.
MB. Jun 15 '11 at 10:59 2011-06-15 10:59
source share