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

The correct approach, in general, is your Case 1. This maintains a single responsibility for the class (whatever it does) without coupling it to a specific persistence mechanism (a disk).

You’re looking at a specific case of a more generalized problem: Serialization. It’s good and OK for an object to have some means to indicate how it should be serialized– it’s the only entity that knows what’s necessary to deserialize it, after all. But if you make the object save itself to disk, you’ve tightly coupled that object to a specific implementation.

Instead, consider creating an interface that a generalized “writer” can use to “serialize” the object to whatever that writer serializes to. This way, you’ll be able to serialize to disk, to the network, to memory, to whatever you actually need to serialize to. 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)