I would like to know what's the best code design when storing and retrieving data from a database when working with objects and classes.
I could do this in two ways.
In the class constructur I query the database and stores all info in instance variables inside the class and retrieve them with getters/setters. This way I can always get any information I want, but in many cases wont be needing all the information all the time.
public class Group {
public int GroupID { get; private set; }
public string Name { get; private set; }
public Group(int groupID)
{
this.GroupID = groupID;
this.Name = // retrieve data from database
}
public string getName()
{
// this is just an example method, I know I can retrieve the name from the getter :)
return Name;
}
}
The other way is to create some methods and pass in the groupID as a parameter, and then query the database for that specific information I need. This could result in more querys but I will only get the information I need.
public class Group {
public Group()
{
}
public string getName(int groupID)
{
// query database for the name based on groupID
return name;
}
}
What do you think is the best way to go? Is there a best practice to go with here or is it up to me what I think works the best?