How to handle inheritance in Google Protocol Buffers 3.0?
Java equivalent code:
public class Bar {
String name;
}
public class Foo extends Bar {
String id;
}
What would be Proto equivalent code?
message Bar {
string name = 1;
}
message Foo {
string id = 2;
}
Protocol Buffers does not support inheritance. Instead, consider using composition:
However, that said, there is a trick you can use which is like inheritance -- but which is an ugly hack, so you should only use it with care. If you define your message types like:
These two types are compatible, because
Foo
contains a superset of the fields ofBar
. This means if you have an encoded message of one type, you can decode it as the other type. If you try to decode aBar
as typeFoo
, the fieldid
will not be set (and will get its default value). If you decode aFoo
as typeBar
, the fieldid
will be ignored. (Notice that these are the same rules that apply when adding new fields to a type over time.)You can possibly use this to implement something like inheritance, by having several types all of which contain a copy of the fields of the "superclass". However, there are a couple big problems with this approach:
Foo
to typeBar
, you have to serialize and re-parse; you can't just cast. This can be inefficient.