I'm trying to decide whether it is better to use static methods for loading/saving objects, or use constructor/instance methods instead.
So, say for object Project, the instance version would be
public Project(path) { // Load project here }
public void Save(path) { // Save project here }
And the static version would be
public static Project Load(path) { // Load project and return result }
public static void Save(path, proj) { // Save project }
So, which do you prefer?
Neither. Favor extracting persistence logic from your domain model and into a separate layer of classes.
(from a comment left in ChrisW's answer) Regarding the details of the domain object leaking into another class: you can restrict the visibility of those details, if your language permits, by using package-privacy/internal access. Alternatively, you can use a DTO approach.
If there is no state to be maintained, only behavior, then use the static approach. However, if the Project object needs to have state, then the constructor/instance method should be used.
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