I'm not sure which of these two "patterns" is the best. Currently I use option A (in conjunction with a provider for implementing persistence), but I'm now erring towards B, especially in light of unit tests being able to use the "dependency injection" model.
Option A:
class ClassA
{
ClassA() { }
Save();
static List<ClassA> GetClassAs();
}
Option B:
class ClassA
{
ClassA() { }
Save();
}
class ClassARepository
{
ClassARepository() { }
List<ClassA> GetClassAs();
}
I think what I'm asking is, is it good practice for a class to expose static methods that return collections of instances of itself?
There seems to be a general consensus that Option B is the better choice. Looks like I have plenty of refactoring ahead :S
Option B looks a bit like the ActiveRecord pattern (I Assume the Save method in ClassA will use the ClassARepository ? ), which is good in some situations, but, if you have rather complex domain-model, I wouldn't use the 'ActiveREcord' pattern.
Instead, I would use such a model:
public class ClassA
{
public int Id {get; private set;}
public string Name {get; set;}
}
public class ClassARepository
{
public ClassA Get( int id );
public void Save( ClassA item );
}
Which means that all persistence related logic is put in the ClassARepository class, and ClassA has also no direct access to the repository.
You either divide completely persistence of the object from the data and logic or keep all in the one class. Move 'Save' to 'ClassARepository' or keep 'GetClassAs' inside 'ClassA'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With