Google
 
Web unafbapune.blogspot.com

Tuesday, November 11, 2008

 

A little Java constructor pattern

Say we have a class Item:
public class Item {
final String name;
final float val;
final int size;

public Item(String name, int size, float val) {
this.name = name;
this.val = val;
this.size = size;
}
}
and we'd like to initialize an Item array with some values:
Item[] items = {
new Item("A", 3, 4),
new Item("B", 4, 5),
...
};
Wouldn't it be nice if we can simplify it to:
Item[] items = {
Item("A", 3, 4),
Item("B", 4, 5),
...
};
?

Couldn't this be easily done by defining a static factory method with the same name as Item, and then use it via static import ?
public class Item {
// ... same as above

// A static factory method for the syntactic sugar
public static Item Item(String name, int size, float val) {
return new Item(name, size, val);
}
}
Usage:
import static Item.Item;
...
Item[] items = {
Item("A", 3, 4),
Item("B", 4, 5),
...
};

Comments:
nice style. i like it.
 
That is sweet. New idiom for static method factories perhaps.
 
A lot of work to avoid the keyword new. Plus I find the use of static import uglier than using new. Magic on top of magic.

One could argue that you've added value in that you've got a factory method with room to do the abstract factory pattern - but there are better ways to do that nowadays with IoC.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?