Tuesday, November 11, 2008
A little Java constructor pattern
Say we have a class Item:
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 ?
and we'd like to initialize an Item array with some values: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;
}
}
Wouldn't it be nice if we can simplify it to:Item[] items = {
new Item("A", 3, 4),
new Item("B", 4, 5),
...
};
?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 ?
Usage: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);
}
}
import static Item.Item;
...
Item[] items = {
Item("A", 3, 4),
Item("B", 4, 5),
...
};
Comments:
<< Home
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
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.
<< Home