Constructors and Creation Methods

Sometimes a constructor doesn’t communicate intention very effectively. This could be because instantiating the class in question isn’t as straight-forward as “creating a new object”, or because there are many alternative constructors. In those circumstances it might be useful to use well-named static or non-static methods to create instances of the class instead.

Joshua Kerievsky introduced the term Creation Method for these kinds of methods. The GOF pattern Factory Method is similar as it includes a subset of all possible Creation Methods.

So, how does a Creation Method differ from a constructor, semantically? When should one use one or the other?

Is computation required?

I tend to use a Creation Methods when the instance creation requires much computation. In one sense, it is very similar to when to use properties and when to use Get-methods in VB/C#.

Possibly, a Creation Method which does a lot should be seen as a separate responsibility and moved to a a separate Factory class. This is similar to what Joshua Kerievsky discusses in Encapsulate Classes with Factory, that some developers might not like having a class which has a Factory responsibility as well as its normal responsibility. In the end, I guess it’s a matter of taste.

Do you actually get a new object?

A Creation Method may be used when there is a finite set of possible objects to create. In such a case, a well named Creation Method may indicate that you cannot actually create a new object, but rather get one of the already defined.

An example would be the Java class Charset. There is a limited number of possible charsets (or at least number of charsets the system will understand), and therefore it does not provide a public constructor, but rather uses the method forName(String). You would use the following code to create a Charset object.

Charset c = Charset.forName("ISO-8859-1");

Other reasons

Another reason to use a Creation Method could be to hide the fact that it’s actually a (private) subclass which is being instantiated. In other words, that the Creation Method is actually a true Factory Method. See for instance the Money example in Kent Beck’s Test-Driven evelopment.

You’ve got more ideas on what differs Creation Methods and constructors? Post a comment.

There are no comments on this post

Leave a Reply