Friday, May 27, 2005

Static Factory Methods

Static factory methods is sometimes used instead of constructors (Bloch 2001).

Problem with constructors is that constructors do not have their own name, but same name as its class (Bloch 2001):

  • the name does not describe what the constructor returns (Bloch 2001).
  • must create a new object when invoked/called (Bloch 2001)
  • only one constructor with a given signature (Bloch 2001)
  • constructors can't return subclasses of class (Bloch 2001)

Definition: A static factory method is a public method that returns an instance of its class.

Naming Conventions

Bloch (2001) argues that adhering to standard naming conventions for static factory methods will make them readily distinguishable from other static methods, and says that the two names valueOf and getInstance are becoming common, the idea beeing that valueOf should return an instance that has the same value as its parameters and getInstance should return an instance described by its parameters.

However, it seems that both names are not much in use as of j2se 1.5.0. valueOf seems currently to be used mostly for type wrappers, and getInstance does not seem to be used that much. Perhaps a problem with standard naming conventions for static factory methods is that the name no longer really reflects what the method does. And after all, there already is a standard naming convention for constructors.

Examples of static factory methods

  • the public static Integer valueOf(int i) { method of class Integer
  • Conclusion

    * static factory methods have names (Bloch)
    * can return existing objects (Bloch)
    * can return subtypes (Bloch)
    * new is the standard way of creating objects (Bloch)
    * valueOf should return an instance with the same value as the parameters (Bloch)
    * getInstance should return an instance described by the parameters (Bloch)
    

    No comments: