Search code examples
c#design-patternsfile-format

Pattern for varying data structures


I am working on a project that requires a fixed length file to be deserialized into an object structure.

The file has this basic structure:

-- file header data
----- groups
----------details

Normally this would be an easy task, however this particular file format has about 10 different sub-formats for the detail records. For example, if the detail row starts with a code '7' then its format ABC, with vastly different fields than format XYZ (rows starting wtih '8').

So my question is, what design pattern could I possibly use to implement this in an elegant fashion?

My first thought is to make a generic detail class with a DetailType enumeration property, and also have a property of type IDetailSpec called SpecData. IDetailSpec would really just be a marker interface. Then whenever I worked with the Detail object I would check the DetailType property and do a cast on the SpecData property depending on the context.

This however, feels "wrong" :)

Any ideas are welcome!


Solution

  • I would suggest making a base class that handles the fields that remain the same between all of the different detail types. (The data that changes would "deserialize" into a single field, for now.) Then you owuld have a different child class for each type of detail record and use a factory-type pattern to create instances of appropriate child classes based on the detail row's code. Each child class would deserialize from the base class object's "detail data" field.