Saturday, 22 November 2008

Item 1: Consider static factory methods instead of constructors

This item explains how to deal with situations where instances of a class have several similar ways of being constructed. Instead of adding several constructors to a class which might be difficult or error prone to use, static factory methods are written with names that clarify their purpose. This allows the class designer to disambiguate similar (or indeed identical) constructor signatures so that the class user is less likely to use the wrong function to create an instance of the class.

The item discusses several advantages of static factory methods:
  1. their self documenting nature, and their extra flexibility when construction parameter sets are ambiguous
  2. their use with object caches like the GoF Flyweight pattern and other "instance-controlled" classes (a term which is new to me although the author impies that it is idiomatic)
  3. their use with derived class hierarchies particularly for implementation hiding where the concrete instance returned by the factory method is of a non-public type, this allows implementation variation depending on construction arguments or other mechanisims such as being able to return types which have been registered at runtime in a so called "service provider framework"
  4. they may be used to simplify parameterized type construction by eliminating the duplication of type parameters by the user by letting the compiler deduce the types;
and two disadvantages:
  1. if all construction is done via static factories and all constructors are non-public then users cannot derive from the classes in their packages - although this would be an advantage if it was desired by the class designer
  2. without careful documentation or standardized naming, it isn't obvious to users that the factory methods are what they are and should be used to instantiate objects of the class
As with the GoF book which also classifies items (in their case more formally as "Design Patterns") in a catalogue, it should be noted that choosing item 1 verses item 2 requires an analysis of the number of construction parameters and whether any of them are optional. In particular static factories may not be suitable with optional arguments.

I disagree a little with the implied similarity to items in this book and design patterns, the first two items (which is as far as I have read) are not design patterns just examples of idiomatic Java usage. Design patterns deal with relationships between classes in a mostly language independant way, whereas this book and similar ones for C++ rarely give any advice on how classes should collaborate with each other. Nevertheless the information is valuable and I am only querying the references to the GoF book that imply these items are design patterns.

Bill Somerville

No comments: