Say I have this simple class
public class MyEntity
{
public DateTime DateUpdated { get; private set; }
public string Author { get; private set; }
public string Comment { get; private set; }
public void AddComment(string comment, string author)
{
Author = author;
Comment = comment;
DateUpdated = DateTime.Now;
}
}
I have made the setters private to encapsulate the class and added the AddComment method to add some behaviour to my class. This works perfectly fine when creating a new object but when I want to load the Entity from the db the DateUpdated is of course set to the current date which I would like to avoid.
Is there any patterns I could use to avoid making the DateUpdated setter public as that does seem to break my nice encapsulation and messing up the clean interface of the class? The class is of course just an example of a more generic problem.
The closest I have got to now without making more public constructors is creating a private constructor which I access through a public static method.
Use a constructor that takes parameters matching the fields of the object.
This will allow you to populate the objects on startup and keep them immutable.
public MyEntity(DateTime dateUpdated, string author, string comment)
{
DateUpdated = dateUpdated;
Author = author;
Comment = comment;
}
Look into the Memento pattern for re-hydrating your object. Use the constructor only for creating a new instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With