FlatPenguin
FlatPenguin

Reputation: 121

Static Factory Methods getType & newType examples

In Effective Java , Item 1, towards the end of the this section on Static Factory methods, Joshua Bloch describes common names for static factory methods. Two of these names, getType and newType, are a little confusing for me.

Quote [Bloch, p. 10]

getType - Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

newType - Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

What would be the use case for having static factory methods in a different class? Is there an example of this pattern in use within the Java API?

Upvotes: 0

Views: 407

Answers (1)

Jason C
Jason C

Reputation: 40376

What would be the use case for having static factory methods in a different class?

The use case is simply, well... when you've got static factory methods in a different class. Your code could conceivably be organized in such a way that this works out to be more appropriate. There isn't really "the" use case, it very much depends on your situation, requirements, and style.

The getType() and newType() are not meant to be taken literally; they are meant to indicate a naming convention as in Something.newWidget() or whatever.

An example of this in the Java API is e.g. Channels, where it makes sense to organize multiple related factory methods in the same class. Semantically, a method named Channels.newInstance() wouldn't really make a lot of sense, since it doesn't instantiate a new Channels.

Another example is the commonly used Executors.

A lot more examples in the API can be found by browsing the 'n' section of the documentation index (look for "new*").

None of this stuff is really hard and fast concrete rules, just general guidelines and options. What you need to do is whatever you need to do make sure your code is clear, concise, maintainable, and flexible. So you make the call when designing and writing your software.

Upvotes: 1

Related Questions