A coworker recently brought up an entertaining question, although we both agreed that it was unimportant overall: what do you name your factory methods?
Some observations:
- The
java.xml.*package usesnewXXX()for the factories, e.g.DocumentBuilderFactory.newInstance(),DocumentBuilder.newDocument(). - The
java.xml.*package usescreateXXX()for the builders, e.g.Document.createXXX(). java.lang.Class.newInstance().java.lang.Array.newInstance().- Design Patterns, the GoF book, uses
createXXX(). - .NET uses
System.Activator.createInstance(). - COM uses
CoCreateInstance(). - The Wikipedia article on Abstract Factory uses
create.
We traded some ideas, but we soon found that the criteria we used were often too vague or hard to use. In the end, we agreed that create was probably the best for everything, because:
- It’s a simple rule, with no exceptions, i.e. avoid thinking effort on something so minor.
createXXX()is more versatile thannewXXX(). There are cases wherenewXXX()sounds a little awkward (perhaps because “new” is an adjective)
createXXX also follows the common principle that method names are verbs, class names are nouns.
A fun exercise, but I hope no one actually spends that much time on issues like these – rather, I wish people didn’t, since I know some people do.
Advertisement