Search code examples
javadesign-patternsconstructorfactory-patterneffective-java

Do we ever need to prefer constructors over static factory methods? If so, when?


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:

  1. They have names!
  2. We have total instance control (Singletons, performance, etc.)
  3. They can return a subtype/interface
  4. Compiler can provide type inference

Disadvantages:

  1. Private classes cannot be subclassed
  2. 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:

  1. Is it good practice to always use static factory methods by default over constructors?
  2. Is it ever justified to use constructors?
  3. 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.


Solution

  • static factories still have to call a constructor in the end. You can move most of the functionality into the static factory, but you cannot avoid using a constructor.

    On the other hand for simple cases, you can have just a constructor without having a static factory.

    Constructors are the only way to set final fields, which IMHO are preferable to non-final fields.

    You can use constructors can in sub-classes. You cannot use static factories for a sub-class.

    If you have a good dependency injection framework to build dependencies of a component, you may find that static factories don't add much.