0

A while ago I finished the highly recommended "Working Effectively with Legacy Code" by Michael Feathers. In a final confirmation of my increasing senility I am absolutely convinced seeing a code sample in that book where he defined a struct that included a version number as one of its fields.

However, I am completely unable to find again where I may have seen this code sample. Does anyone know if it was indeed in that book?

Otherwise, is it generally a good idea to include a version number in a struct? How/when might it be used?

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
lindelof
  • 34,556
  • 31
  • 99
  • 140
  • 3
    This might be useful if you de/serialize the struct, because your definition of a struct could change and if you previously saved the version number, you still can have a backwards compatible deserializing code. – Anthales Apr 22 '12 at 19:05
  • It could also be useful for a few "top-level" structures, e.g. for "singleton" structures (those having a single instance). If you have version number, don't forget the code to check its compatibility. – Basile Starynkevitch Apr 22 '12 at 19:16
  • Meh, just putting a field in the struct, at the beginning, that contains the structure size works well. Now you know *two* things that are important. If this is really about legacy code then finding this out now is surely too late. – Hans Passant Apr 22 '12 at 19:35

1 Answers1

3

Normally it is the other way round. Persistent, serialized data structures on external media would be versioned (contain a version number), while the in-memory structure would exist in a single version only, possibly generalized enough to be able to represent multiple persistent formats in a unified model, and typically not contain the version number.

However, this versioning approach implies that if you modify (edit, update) a data structure and save it back, it will typically be encoded into the latest available format, for good or bad. Occasionally this is not desirable. For example, this could break compatibility with a lower software release or lower capability node/process/system that created this piece of data and that may still need to access it. In such circumstances, you might decide to store the format version even in the in-memory struct and stick to it when serializing, to avoid such "implied format upgrades", or to prevent types of updates that the older format cannot represent or should not allow.

Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75
  • +1: And if you want the new software to save data in the old format, you will somewhere need the old version number around to get the old serialization output. It might or might not be in the in-memory structure. – Jonathan Leffler Apr 22 '12 at 21:28