3

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, it should be noted that the thing that uses IPeopleRetriever should not be the thing that creates an instance of IPeopleRetriever.
0

It depends. For what you're saying, I'd say no and create another class to populate your Person class. However, there are some times when you may want to return a List<T> from T. One example is a tree. You could have a class with a method that returns a generic list of the same type.

public class Node()
{
    public List<Node> GetChildNodes()
    {
        //etc...
    }
}

That being said, your example doesn't really sound recursive in any way, so I'd have another class actually create the List<T>. It's really all about dependencies. If you ever want to use your class in a way that doesn't require a list of Person objects, then your class could be creating objects unnecessarily.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.