Creation of Objects: Constructors or Static Factory Methods

  • 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.

Leave a Comment