Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Design - Returning a List<Object> From <Object>

Tags:

c#

.net

oop

Given a simple class:

public class Person 
{
    public string FirstName;
    public string LastName;

    public string GetFullName() 
    {
     return FirstName + LastName;
    }
}

The user of this class will populate a List<Person> object by reading an Xml file or some other data source. Should the logic for populating the List be in the Person class or should it just remain in the calling class? In other words, should there be a public List<Persons> GetPersons() method in the Person class or in the calling class? Or should the data accessor be in another class altogether?

I know this is a rather simplistic question but I'm just curious how others typically do it.

like image 997
Mike Avatar asked Apr 02 '26 19:04

Mike


1 Answers

What if the data store changes at a later time? What if the Person's wil no longer be stored in an XML file but rather in a Database? Now you need to change the Person class again. I would say have some kind of interface called "IPeopleRetriever" or something:

public interface IPeopleRetriever
{
   IEnumerable<Person> GetPeople();
}

Then, have a class called XMLPeopleRetriever:

public class XMLPeopleRetriever : IPeopleRetriever
{
   public IEnumerable<Person> GetPeople() { ... }
}

That way, the consumer of your IPeopleRetriever needs to know nothing about where the Person's came from.

like image 91
BFree Avatar answered Apr 04 '26 08:04

BFree



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!