Cameron MacFarland
Cameron MacFarland

Reputation: 71916

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?

Upvotes: 2

Views: 428

Answers (3)

moffdub
moffdub

Reputation: 5314

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.

Upvotes: 10

ChrisW
ChrisW

Reputation: 56123

For the saving, I see no advantage to making Save a static method.

For the loading, defining a static Load method is better if Project is an abstract base class; but otherwise, defining and invoking a constructor is more idiomatic.

Altenatively I agree with moffdub's answer, if-and-only-if the functionality is big enough to make the persistence logic worth splitting/separating away into some other class. However, if you do this then the details of the data contained in Project are no longer private (and instead, these details must be shared with the class which loads and saves the Project instances).

Upvotes: 1

geowa4
geowa4

Reputation: 41833

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.

Upvotes: 1

Related Questions