In a webapp, i have a data-model (let's call it Item). The data of this Item is filled by two methods. The first method is a XML parser (data import), the second reads the Data from a Database (while parsing the website).
I see two possible ways to implement this class:
first way:
public class Item() {
public void parseFromXML(String xml) {
//xml parse code
}
public void loadFromDB() {
//load from Database
}
}
so i can create a new Item with:
Item myItem = new Item();
myItem.parseFromXML(xml);
or
Item myItem = new Item();
myItem.loadFromXML();
second way:
public class Item() {
public static Item getItemFromXML(String xml) {
Item i = new Item();
//xml parse code
return i;
}
public static Item getItemFromDB() {
Item i = new Item();
//Database load code
return i;
}
}
with this way i can instantiate an item like this:
Item myItem = Item.getItemFromXML();
or
Item myItem = Item.getItemFromDB();
My question is: Which is the better way, and why? I personally prefer the 2. way, because the programmer, which will use this class (at this time only me) will never get a void Item-object (can i throw an 'FalseInstantiateMethod'-Exception in the constructor?).
(sorry, my English is not the best, i hope you can understand it anyway)