I often find myself in a quandary where the serialization code for the class is put, and wondered what other people thought about this issue.
Standard Bog serialization is not a problem. Just decorate the class in question.
My question is more suitable for classes that are serialized by different protocols or in different formats and require some thought / optimization for the process, rather than just blindly serializing decorated properties.
I often feel that itβs cleaner to keep the code in the same format in my class. It also allows you to add additional formats by simply adding a new class. eg.
class MyClass { } Class JSONWriter { public void Save(MyClass o); public MyClass Load(); } Class BinaryWriter { public void Save(MyClass o); public MyClass Load(); } Class DataBaseSerialiser { public void Save(MyClass o); public MyClass Load(); }
However, this often means that MyClass needs to expose much more of its internal components to the outside world so that other classes can serialize efficiently. This seems wrong and contradicts encapsulation. There are ways around this. for example, in C ++ you could make serialiser a friend, or in C # you could expose certain elements as an explicit interface, but it still doesn't feel great.
Another option, of course, is to let MyClass know how to serialize itself to / from different formats:
class MyClass { public void LoadFromJSON(Stream stream); public void LoadFromBinary(Stream stream); public void SaveToJSON(Stream stream); public void SaveToBinary(Stream stream);
This seems more encapsulated and correct, but it associates formatting with the object. What if some external class knows how to serialize more efficiently due to some context that MyClass is not aware of? (Perhaps a whole bunch of MyClass objects reference the same internal object, so an external serializer can optimize only by serializing it once). Also, if you want a new format, you need to add support to all your objects, and not just write a new class.
Any thoughts? Personally, I used both methods depending on the exact needs of the project, but I just wondered if anyone had any serious reasons or against a particular method?