Jared Feldman
Jared Feldman

Reputation: 23

Is this proper OOP design? Static function return instance of object

I have a database table representing people. I am writing a WebService that will use this class and I don't want to get all the people every single time. Is the 'correct' way to go about this? Is there some sort of design pattern that is close to this?

This is a dumbed down example of what I am actually doing, all of the setters in each of the properties would save to the database.

namespace Example
{
    class Person
    {
        private int _id;
        private string _name;
        private int _age;

        public int ID { get { return _id; } set { _id = value; } }
        public string Name { get { return _name; } set { _name = value; } }
        public int Age { get { return _age; } set { _age = value; } }

        private Person(int id)
        {
            _id = id;
            // Query database and set values
        }

        public static Person GetPersonByID(int id) {
            return new Person(id);
        }
    }
}

Upvotes: 1

Views: 102

Answers (2)

sarin
sarin

Reputation: 5307

You have shown one way that will work but it's mixing the plumbing with the object itself which isn't great for passing the object round and maintainability.

Another very common way is the Repository Pattern. In this you would have a PersonRepository Class that is designed to GET\UPDATE instances of the Person class. Repository Pattern example. Your repository interacts with the database and serves up instances of Person. Code nearer your UI doesn't need to worry about any Entity Framework \ Data access logic. You UI simply asks for Person objects from the Repository and displays them. This demonstrates good separation of concerns which keeps code clean and helps future maintenance.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77304

In this case, I'd scrap the method. It does not anything the user could not do on his own while it's unintuitive to use. Having a constructor is the normal operating behavior.

Generally speaking, this could be a pattern to use if this function does something that can not be done in a constructor.

Personally, I'd remove all logic from the person class. It's the class' job to be a person. A person can be without any database. If you want to load persons from a datasource, make a datasource class and have one of it's methods return a person.

class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class DataSource
{
    public void Save(Person p)
    {
       // save person to database
    }

    public Person LoadById(int id)
    {
       // load person from database
    }
}

Upvotes: 5

Related Questions