Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which class structure is more desirable?

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?

Edit

There seems to be a general consensus that Option B is the better choice. Looks like I have plenty of refactoring ahead :S

like image 685
Paul Suart Avatar asked Nov 20 '25 00:11

Paul Suart


2 Answers

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.

like image 87
Frederik Gheysels Avatar answered Nov 24 '25 22:11

Frederik Gheysels


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'.

like image 24
Mykola Golubyev Avatar answered Nov 24 '25 22:11

Mykola Golubyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!