Sunday, December 14, 2008

Savio's Notes: Java Book: Effective Java - Chapter 2 - Item 1

The first in a series of notes about the book Effective Java by Joshua Bloch will cover Chapter 2 - Item 1. Some sharp readers would be wondering why not Chapter 1. Those who have read the book will be aware that Chapter 1 is more of an introduction to the book and it also will explain why I didn't make any notes for it. So worry not, you haven't missed anything yet!

Item 1

Use static factories instead of constructors
I never thought of it in these terms, but I had always felt uneasy whenever I used the new operator in code. I always tried to never to use the new operator and have either a third utility class that returned a newly minted instance or have a static method that did the same.

But Joshua Bloch puts it more eloquently and convincingly and here are his reasons:
  1. Static factories unlike constructors can have more meaningful names which in turn help code readability
  2. Static factories unlike constuctors do need to create a new object every time. They could implement some kind of caching mechanism to enable reuse of instances
  3. Static factories unlike constuctors can return sub-types of their return types
The book also lists disadvantages of this item as:
  1. Classes without public or protected constructors cannot be sub-classed. But he goes on to state that this may be an advantage as it forces the use of composition over inheritance which is further elaborated in Item 14
  2. Besides the use of naming conventions there is no way to distinguish a static factory from other static methods in the class
In conclusion the book recommends using static factories unless you are convinced that it dooesn't suit your needs. Alternatively if you are confused go with constructors as they are the norm.

From my part, I will now be trying this pattern more often to put in private constructors and use static factories. Maybe the convention to use would be to have the static factory name as getInstanceUsingXxxx(...)