Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation of Objects: Constructors or Static Factory Methods

I am going through Effective Java and some of my things which I consider as standard are not suggested by the book, for instance creation of object, I was under the impression that constructors are the best way of doing it and books says we should make use of static factory methods, I am not able to few some advantages and so disadvantages and so am asking this question, here are the benefits of using it.

Advantages:

  1. One advantage of static factory methods is that, unlike constructors, they have names.
  2. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  4. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

Disadvantages:

  1. The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
  2. A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10

I am not able to understand the fourth advantage and the second disadvantage and would appreciate if someone can explain those points. I would also like to understand how to decide to use whether to go for Constructor or Static Factory Method for Object Creation.

like image 909
Rachel Avatar asked Jan 06 '11 16:01

Rachel


2 Answers

  • Advantage 4: When using a constructor, you have

    Foo<Map<Key, Value>> foo = new Foo<Map<Key, Value>>();
    

    vs

    Foo<Map<Key, Value>> foo = Foo.createFoo(); // no need to repeat
    

    this advantage will be gone in Java 7, when the diamond syntax will be introduced

  • Disadvantage 2. You can't easily tell whether a given static method is used for constructor, or for something else.

As for how to choose - there is no single recipe for that. You can weigh all of the above advantages and disadvantages given a use-case, but most often it will just be a decision driven by experience.

like image 176
Bozho Avatar answered Sep 22 '22 05:09

Bozho


If you know the concrete type of the class you are trying to create, then calling the Constructor is fine.

Static Factory Methods are nice when you're not entirely sure how to construct the object you need.

The Factory Method still calls the Constructor on the concrete type, but the method handles the decision on what kind of concrete class to instantiate. The Factory Method then returns an Interface type (rather than a concrete type) so that the concrete type is hidden from the caller.

like image 35
Justin Niessner Avatar answered Sep 19 '22 05:09

Justin Niessner