tags:

views:

31

answers:

1

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)

+3  A: 

Wouldn't it be better to use an ItemFactory:

ItemFactory factory = new XMLItemFactory();
URI uri = new File("item.xml").toURI();
Item item = factory.create(URI);

or the database one:

DatabaseItemFactory factory = new DatabaseItemFactory();
factory.setDataSource(dataSource); // Use DI here
URI uri = URI.create("item://id=123");
Item item = factory.create(URI);

The advantage is that you (or others) can easily provide new ItemFactory implementations, e.g. to use Java Serialization or to store item in an OODB or to remotely load it using a WebService. Much better to separate the creation/loading of an object from various locations into separate classes.

I would not want to have database-dependencies in my domain object model.

mhaller
"I would not want to have database-dependencies in my domain object model." - +1 just for this. Excellent advice.
duffymo
+1 Better approach.
BalusC
Thank you, i will do it your way...
mg