Possible Duplicate:
Consider providing static factory methods insteads of constructors
This maybe a controversial question and may not be suited for this forum (so I will not be insulted if you choose to close this question).
It seems given the current capabilities of Java there is no reason to make constructors public … ever. Friendly, private, protected are OK but public no.
It seems that its almost always a better idea to provide a public static method for creating objects. Every Java Bean serialization technology (JAXB, Jackson, Spring etc…) can call a protected or private no-arg constructor.
My questions are:
- I have never seen this practice decreed or written down anywhere? Maybe Bloch mentions it but I don’t own is book.
- Is there a use case other than perhaps not being super DRY that I missed?
EDIT: I explain why static methods are better.
.1. For one you get better type inference. For example See Guava’s http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained
.2. As a designer of the class you can later change what is returned with a static method.
.3. Dealing with constructor inheritance is painful especially if you have to pre-calculate something.
.4. More reasons here: https://stackoverflow.com/a/3852556/318174
I should have posted that this is for public API like code. I frequently violate all sorts of rules (like using direct field access) for Unit Testing, convenience, and cause I’m lazy. So when I meant ever, I meant your releasing it into the wild.
If following is how the method looks
then would prefer to have a public no-arg constructor.
If I have to call some method like that, it will make me feel that it is doing something to construct the object but in reality it isn’t.
I don’t think there is any point in having a method that doesn’t do anything but invoke the constructor itself.