I'm trying to decide what's the best approach to instantiate a particular class. Basically there are two use cases for it: instantiate it in order to save a new entry to the database and fetch an existing entry from the database (and maybe edit the fetched entry and save it back to the database).
The issue I'm having right now is that I can't decide which mechanism for instantiating that class and populating its fields to choose. Say I have this class
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
And here are the usecases. If you want to fetch a student for the database, the code looks something like:
Student student = MyLibrary.GetStudent(id);
And if you want to create a new student and add it to the database:
Student student = new Student();
student.FirstName = "James";
student.LastName = "Jackson";
// etc
MyLibrary.CreateStudent(student);
The massive issue with this approach is that all the setters are public and I absolutely do not want this. But at the same time I want the user to be able to populate most of the Student
fields freely (maybe with the exception of Id
.
I'm thinking the builder pattern could be employed in here. This way I can keep the setters private and force the user to create read-only students via the builders. However it then becomes really awkward if the user wants to update a field and save it to the database:
var student = MyLibrary.GetStudent(id);
var newStudent = new Student.Builder(id).FirstName("NewFirstName").LastName(student.LastName)...etc...Build();
MyLibrary.CreateStudent(newStudent);
Basically my only issue with the builder approach is that the code can get quite awkward and tedious if you want to update an existing entry. Some of the classes I have can have around 10 fields and it's not great having to copy 9 of the fields and update one. But it may be much nicer than having a class with public setters.
What other options do I have?