What is the proper (or a good) design if I need to have a class that loads its data from a file (while keeping the load functions in a different class)?
This is what I have now. Can’t help but think there is a better way to structure it all though. The part that is tripping me up is when Loader has to call a method in Primary before continuing.
class Primary {
public int x1, x2, x3; //data that is read from file or calculated
public void LoadPrimary {
Loader L = new Loader();
L.Load(this); //pass self as parameter (this can't be the best way though)
}
public void DoStuff() {
x1++; x2--;
}
}
class Loader {
public void Load(Primary PrimToLoad) {
PrimToLoad.x1 = 2; PrimToLoad.x2 = 4;
PrimToLoad.DoStuff(); //call a method in the calling class (better way for this?)
PrimToLoad.x3 = 6;
}
}
class Stub {
public void SomeMethod() {
Primary P = new Primary();
P.LoadPrimary();
}
}
In my real code I am using the Loader class to encapsulate a few different formats read from various sources (so there are multiple Load functions), otherwise I would just include the function in Primary and be done with it. Is there a way to have the Loader class return the Primary instead of void (where now it is passing a Param). It seems too “coupled” to be good design this way.
Any suggestions on a better way to accomplish this scenario? I assume it is pretty common but just don’t know enough about class design or terminology to find an answer on google/SO/etc (how do you search the dictionary for a word you can’t spell).
Updates/Notes
Both the answers (so far) point towards Factory pattern. Does that mean that for each Load method I have to have a separate class? Seems like overkill in my particular case. Doesn’t that also imply that my Stub class has to know/decide the format of a file (so it can call the correct factory class) instead of just letting the Primary class worry about it? Seems to be trading coupling for encapsulation.
Definitely know that I should be using properties (am actually) and an interface (am actually) but wanted to simplify it down for the question. Didn’t think about the injection aspect which is a good suggestion.
If anyone can update their answer to show how multiple load functions would work (please keep them simple) I will most likely accept. I am also considering moving the load functions back into the Primary class as an alternative solution.
This looks like a pretty straightforward example of the Factory pattern. You don’t want the object being created to know about the factory though. So rip out LoadPrimary(), and do this instead: