newSomething() instead of new Something

I was looking at one of the nio demonstration examples and noticed this line:


// Charset and decoder for ISO-8859-15
private static Charset charset = Charset.forName("ISO-8859-15");
private static CharsetDecoder decoder = charset.newDecoder();

The first one is moderatly understandable since the method won’t create a new object. But the second line is it really necessary ?

What would be the problem if they simply use this:


private static CharsetDecoder decoder = new CharsetDecoder(charset);

Off topic: Don’t you wish sometimes you could use C++ syntax like this?


private static CharsetDecoder decoder(charset);

The difference is that new CharsetDecoder(charset); must return a class of type CharsetDecoder, where as charset.newDecorder() can return a subclass.

Often this technique is used when the class in question is abstract and you are trying to hide the implementation details.

It’s utilzing the Factory Method Design Pattern. Definetly one of the more useful deign patterns in my experience.

I never actually do this myself (mostly out of laziness), but I still think all constructors should be forced private. Factory methods are cute.

Strange how the “new” operator is looking so limited at the moment: it must allways return a new object (not an already existing link to some static object) and it must be a class of the type used in the operator (not a subclass of that type).

I wonder why using a “public new” at all to create a new object ?

The usual naming is createSomething rather than newSomething is it not? getSomething seems to be used where there is a backing cache and you don’t expect it to return a unique instance.

The most intuitive name for me would be simply make(args) or create(args). No need for the extra word. Java is already clutered with unnecessary long names.

Ey, in your code you can do what you want, simply use create(), nobody restricts you there, if you think this is enough. But imagine you’ve got a factory-class that can create A-objects and B-objects. Then it would for sure be a good way to call the methods

A createA(); and
B createB();

About this long name issue: I rather have long names than
cnoiasw();

Arne

PS: cnoiasw means createNewObjectInAShortWay

[quote=“arne,post:8,topic:25031”]
When you create an object from a factory isn’t it irrelevant what the real class of the object is ? You are going to work with it using the common base class interface anyway. If you need to make that distinction then perhaps you shouldn’t use a factory and create the object directly from its class.

When i said unnvecessarly long names i wasn’t refereing to abreviated names. I think a name should be as short as possible but wthout being cryptic.