Naming factory methods: create() or newInstance()?

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 uses newXXX() for the factories, e.g. DocumentBuilderFactory.newInstance(), DocumentBuilder.newDocument().
  • The java.xml.* package uses createXXX() 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:

  1. It’s a simple rule, with no exceptions, i.e. avoid thinking effort on something so minor.
  2. createXXX() is more versatile than newXXX(). There are cases where newXXX() 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

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.