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:
- Static factories unlike constructors can have more meaningful names which in turn help code readability
- 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
- Static factories unlike constuctors can return sub-types of their return types
- 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
- Besides the use of naming conventions there is no way to distinguish a static factory from other static methods in the class
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(...)