views:

183

answers:

4

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?

+1  A: 

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.

geowa4
A: 

Why decide? Use both.

Mike Thompson
More code == more maintenance. I'm not a fan of that.
Cameron MacFarland
I'm not so sure about that. The implementation would be shared, so the maintenance would only be in one spot. There is nothing wrong with providing multiple paths into a bit of functionality.
Mike Thompson
+8  A: 

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.

moffdub
+1  A: 

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).

ChrisW
The only real benefit of the static save is it can be moved to another class. I only really included it for completeness. But I agree that if the save is defined on the object it's probably worth using the instance version.
Cameron MacFarland
Regarding the details of the domain object leaking: 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.
moffdub