Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors or Static Methods for Loading and Saving Objects?

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?

like image 539
Cameron MacFarland Avatar asked Jul 06 '26 06:07

Cameron MacFarland


2 Answers

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.

like image 142
moffdub Avatar answered Jul 08 '26 20:07

moffdub


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.

like image 27
geowa4 Avatar answered Jul 08 '26 20:07

geowa4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!