How to design for a future additional enum value in protocol buffers?

glennr picture glennr · May 1, 2012 · Viewed 11.8k times · Source

One of the attractive features of protocol buffers is that it allows you extend the message definitions without breaking code that uses the older definition. In the case of an enum according to the documentation:

a field with an enum type can only have one of a specified set of constants as its value (if you try to provide a different value, the parser will treat it like an unknown field)

therefore if you extend the enum and use the new value then a field with that type in old code will be undefined or have its default value, if there is one.

What is a good strategy to deal with this, knowing that in future the enum may have additional values added?

One way that comes to mind is to define an "undefined" member of the enum and make that the default, then old code will know it has been sent something that it can't interpret. Is that sensible, are there better ways to deal with this situation?

Answer

poolie picture poolie · Jun 18, 2013

Yes, the best approach is to make the first value in the enum something like UNKNOWN = 0. Then old programs reading a protobuf with an enum value they don't recognize will see it as UNKNOWN and hopefully they can handle that reasonably, eg by skipping that element.

If you want to do this you'll also want to make the enum be optional not required.

required, generally, means "I'd rather the program just abort than handle something it doesn't understand."

Note that it must be the first value declared in the proto source - just being the zero value doesn't make it the default.