tags:

views:

183

answers:

2

I'm currently using QDataStream to serialize my classes. I have quite a few number of my own classes that I serialize often. Should I derive QDataStream to create my own DataStream class? Or is there a better pattern than this? Note that these custom classes are used by many of our projects, so maybe doing so will make coding easier.

Another way to phrase this question is: when a framework provides you with a serialization class, how do you handle serializing your own custom-type classes such that you don't have to remember how to serialize them everytime (enhance usability) and also following best software-engineering practices (following patterns).

+3  A: 

That would get out of control very quickly. A better approach is to define operator<< and operator>> between QDataStream and your class. Even cleaner might be to simply have serialization methods on your classes that read/write to a QDataStream (so that you would call for example, obj->serialize(myStream)).

Lukáš Lalinský
A: 

The current way that I'm handling this is as follow:

Rather than deriving from QDataStream, I create a serializer class for each object I need to serialize.

For example, if I have:

class MyOwnClass

I would then create a class called:

class MyOwnClassSerializer
{
public:
  static QByteArray const serialize(MyOwnClass const&);
};

The reason why I didn't add a

QByteArray serialize() const;

to class MyOwnClass is so that people can use MyOwnClass without depending on Qt. Also not all MyOwnClass clients are interested in serializing the class.

Any comments would be appreciated! =)

ShaChris23
The `<<` and `>>` operators would act as the serializer class. They don't have to be defined on the data class, but a standalone functions.
Lukáš Lalinský
Where should I place `>>` and `<<` operators in the way that's best? In a pair of .h and .cpp and for each new data type, I just add to that set of files?
ShaChris23
If you don't want the classes to depend on Qt, then separate files are the only way. Otherwise I'd define them in the same file as the data class.
Lukáš Lalinský
@Lukas, what if MyOwnClass inherits from some other class?
ShaChris23
@Lukas, the best way I can think of for now is to do: *reinterpret_cast<BaseClass const*>( e.g. reinterpret it to be a BaseClass ...but that looks kinda ugly. Is there a better way?
ShaChris23
@Lukas, okay, I just learned more about C++ and am using: dynamic_cast<BaseClass const
ShaChris23