Alex Rivera | Logout

Should an object write itself out to a file, or should another object act on it to perform I/O?

Asked 2009-05-23T13:47:59.037
51

NOTE: Sorry for the long question!

I'm trying to understand some key areas behind object orientation and I couldn't decide one way or another about my particular question.

Let's say I have an object full of lovely data. Class bob.

Bob myBob = new Bob("This string is data");

Let's say I want to save the contents of myBob to an xml file (bob.xml)

Should I have an object act on bob to write the contents out, or should I have myBob do this?

Case 1: Act on object

Writer myWriter = new Writer(myBob, "C:\\bob.xml");

Case 2: Save method

myBob.Save("C:\\bob.xml");

Some people are siding with option one as it means if the code for writing files is changed, it doesn't need to updated across every Save method; promoting code reuse I suppose. My problem with this is getting all the data out of objects which may have private data with no accessor.

The case for option two is that the method only acts on the data held by the object and that's the way it should be. No interference from other objects.

Or is the answer to my question one of those "case dependent" issues? If so, how do you know when one method is prefered over the other?

Edit
Report

2 Answers

10

This is an example of where the Strategy Design Pattern could be used. Your myBob object could have an instance of the class that will write it out. You may want the writer to implement an interface or derive from an abstract class so that the save routine can be easily changed.
Today you are saving to xml, but you might need to eventually persist the object to a database as well. This pattern will allow you to change the save routine easily. You would even have the option to change how you save at runtime.

answered 2009-05-23T14:15:02.180
-3

Do this:

public interface Writable {
    public void Save(Writer w);
}

public interface Writer {
    public void WriteTag(String tag, String cdata);
}

public class Bob : Writable {
    private String ssn = "123-23-1234";
    public void Save(Writer w) {
        w.WriteTag("ssn", ssn);
    }
}

public class XmlWriter : Writer {
    public XmlWriter(Sting filename) {...}
    public void WriteTag(String tag, Sting cdata) {...}
}

Obviously this isn't a complete solution but you should get the general idea.

answered 2009-05-23T14:32:02.427

Your Answer