I have been reading Effective Java by Joshua Bloch and so far it really lives up to its reputation. The very first item makes a convincing case for static factory methods over constructors. So much that I began to question the validity of the good old constructors :).
The advantages/disadvantages from the book are summarized below:
Advantages:
- They have names!
- We have total instance control (Singletons, performance, etc.)
- They can return a subtype/interface
- Compiler can provide type inference
Disadvantages:
- Private classes cannot be subclassed
- They do not stand out in the documentation as constructors do
The first disadvantage can actually be A Good Thing (as mentioned in the book). The second one, I think is just a minor disadvantage and can be resolved easily with the upcoming java releases (annotations for javadoc etc.)
It looks like, in the end factory methods have almost all the advantages of constructors, many many more advantages, and no real disadvantages !
So, my question is basically in three parts:
- Is it good practice to always use static factory methods by default over constructors?
- Is it ever justified to use constructors?
- Why don't object-oriented languages provide language level support for factories?
Note: There are two similar questions: When to use a Constructor and when to use getInstance() method (static factory methods)? and Creation of Objects: Constructors or Static Factory Methods. However the answers either just provide the above list or reiterate the rationale behind static factory methods which I am already aware of.