I am trying to figure out the best design for instantiating an object which requires two separate calls to the data layer through a DAO. The object is not usable until these calls have been made (because it requires the data retrieved from the database). I have come up with three possible solutions:
- Create a method in the DAO itself that gets the necessary data from the database, and then pass the data to the object's constructor. The object is passed back as the return value.
- Create a method in the class that is using the object. This method would make both calls to public methods in the DAO, then instantiate and return the object as in step 1.
- Pass the DAO as a parameter to the constructor of the object. The constructor would then make both necessary calls to the DAO, setting its own member variables without the need for Setters. The DAO is not used other than in the constructor.
Examples, if SomeObject is the object I want to create, and Foo is the class that will make use of it:
1 - DAO Contains the logic:
public SomeObject getSomeObject(){ // this DAO method called by Foo class
data1 = getData1();
data2 = getData2();
return new SomeObject(data1,data2);
}
2 - Class that uses object contains the logic:
public class Foo {
...
public void useSomeObject() {
SomeObject obj = createSomeObject();
obj.doStuff();
}
private SomeObject createSomeObject() {
data1 = dao.getData1();
data2 = dao.getData2();
SomeObject someObject = new SomeObject(data1,data2);
return someObject;
}
}
3 - SomeObject takes DAO as parameter and uses it in constructor:
public class SomeObject {
...
public SomeObject(DAO dao) {
data1 = dao.getData1();
data2 = dao.getData2();
}
...
}
Hopefully these examples are sufficient to convey my point. Are any of these solution considered better design than the others? If not, what solution is considered best practice?
Thanks.