Let’s say that I want a class that represents a data structure in memory. In this structure, the first two bytes indicate which version of the structure it is. The order and size of the data that follows depends on the version of the structure.
For example:
Version 1 is a 10-byte structure that looks like this:
- Byte offset 0: Format Version (2
bytes) - Byte offset 2: Data section A
(4 bytes) - Byte offset 6: Data section
B (4 bytes)
Version 2 is a 20-byte structure that looks like this:
- Byte offset 0: Format Version (2 bytes)
- Byte offset 2: Data section A (8 bytes)
- Byte offset 10: Data section B (6 bytes)
- Byte offset 16: Data section C (4 bytes)
I want my class to be able to support both versions without the user of the class having to specify which version to use. That is, when the object is constructed, it should be able to use the Format Version field to determine what its structure should be. Then the getters/setters for each field should be created appropriately based on what the structure is. I also will want to be able to add support for additional structure version in the future. Each new version of the structure will most likely contain all the same fields as the older versions, but perhaps with greater allocation lengths for each of these fields, and perhaps some newly added fields.
As far as I can tell, the only constraint that I have is that the format version field always appears at byte offset 0, and is always 2 bytes long.
So, is it possible to accomplish my goal?
Typically, you’d be creating and using separate classes for each different version of your structure. You’d give them a common interface so you could address and store them by a common type. Those different structure classes could then contain different fields and methods for dealing with the different variations of your data.