mardi 26 mars 2019

Patterns: Translate plain data object object and wire formats

I was inclined to just use the mapper pattern which I use in various places in the app's code for the following task. But I thought it might actually not be the best fit in this particular case:

The task:

  • I need to implement data objects according to a given specification. The specification defines multiple versions for each object type, thus I have for example a class CarV1 and CarV2 representing each version of the specification.

  • I need to translate these models between C++ classes and wire formats (Json, Protocol Buffers), and vice versa.

  • Construction of the objects is rather simple.

As I said, I'd normally use a mapper pattern, define a mapper interface and concrete mappers to map between each format. There are two things though why I ask for your opinion in this case:

  • I'd use the mapper pattern only to map between two, and only two, types of formats, e.g. a database object and a C++ class. I already have a third format in this case, and it's possible that I have to add more formats to translate between in the near future.

  • The versioning adds some complexity on top of the mapping, and I think there needs to be another indirection in between.

I've read about the Translator Pattern [1], but never used it. I think it fits to some degree, but not completely.

I also considered an Abstract Factory. This would allow to create similar objects (in my case versioned objects). But it is not a good fit for mapping between object representations.

What pattern should I use, and why?

Aucun commentaire:

Enregistrer un commentaire