I first heard about CreationMethod from JoshuaKerievsky.
I use CreationMethod when refactoring several constructors into meaningful creation methods. Example:
public class Telephone{ public Telephone(){...} public Telephone(String model){...} public Telephone(String model, double price){...} }Constructors do not always clearly convey intention. When I have several constructors, I refactor them to CreationMethods like
public class Telephone{ public Telephone(String model, doublePrice){..} public createDefaultTelephone(){ } public createTelephoneWithModelAs(String model){ } }-- GunjanDoshi
Presumably that should be "public Telephone createDefaultTelephone(){}" etc. And this kind of creational pattern leaves a bad taste in my mouth somehow - feels like it's just aliasing against the language's built-in syntax. Then again, "constructors" in ObjectOrientedLanguages in general leave a bad taste in my mouth too. :) (I like the idea of object templates better than class templates, and that will be reflected in my design for DefnLanguage assuming I ever get around to writing any of it up.) -- KarlKnechtel
See FactoryPattern, especially the sub category of AbstractFactoryPattern
-
I would assume it should really look like this
public class Telephone{
public Telephone(String model, double price){..} public static Telephone createDefaultTelephone(){ } public static Telephone createTelephoneWithModel(String model){ }}
as you wouldn't want to have to have one instance of Telephone in order to create another Telephone.
An essential fact that is a driver behind this pattern is that sometimes you want to have two constructors with the exact same signature, but with different intents. For example
public class Telephone{
public Telephone(int modelNumber, int modelSubIndex) {} public Telephone(int modelNumber, int defaultAreaCode) {}} (yes this specific example is contrived, but I'm building on the original example)
In this case you'd have to have some other way of indicating to the constructor what you want to do, which means passing in additional arguments, or having "-1" have special significance, etc. Constructors are severely lacking in this manner. However, the CreationMethod can basically overcome this shortcoming, and you just have to understand that these are essentially constructors. (NOT FactoryMethods - that is related but different)