Good names for your factory methods in Java

In addition to well known constructors, it’s sometimes convenient to replace them (or just hide) with static factory method. As we actually could have for our type more static methods, the problem appears how to distinguish our instance creation methods from other ones?

Actually, I found very nice approach on that in Effective Java book, which is as below:

  • valueOf or of - Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods.

  • getInstance - Returns an instance which is described by the parameters but cannot be said to have the same value. In the case of a singleton, getInstance takes no parameters and returns the sole instance.

  • newInstance— Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others.

  • getType and newType – Like getInstance and newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

Advertisements

Leave a Reply

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

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 )

Google+ photo

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

Connecting to %s