Wednesday, August 20, 2014

EJ-1 Consider Static Factory Methods instead of Constructors

Ref: Effective Java by Joshua Bloch

In Item-1 of Effective Java, Mr. Bloch emphasize why and how it is important to use Static Factory methods instead of constructors.

Here is goofy and wasteful way to get Boolean instances

Here is shiny and frugally way to get immutable Boolean instance with static factory method

Lets go over advantages of using static factory methods
1.) Unlike constructors, the have names. If parameters to a constructor do not describe object being returned, a static factory with well choosen name is easier to use and resulting client code easier to read.

Another example is multiple constructors with same signature as I met in stackoverflow.
Two constructors with same signature doing different things.

Can be managed by using static factory methods.

2.) Unlike constructors, they are not required to create a new object each time they're invoked. This is demonstrated as in boolean example above and important to use system resources frugally by avoiding unnecessary instance creation.

3.) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. Mr Bloch exemplifies this advantage with Service Provider Framework pattern.

Finally, he give a list of some common method names to statis factory methods.
  • valueOf
  • of
  • getInstance
  • newInstance
  • getType
  • newType
Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.

No comments: