Best practice for effecting inheritance/polymorphism in proto3

10,647 views
Skip to first unread message

Jeff White

unread,
Oct 18, 2017, 6:04:10 PM10/18/17
to Protocol Buffers
There seem to be 2 techniques to effect pseudo-inheritance/polymorphism.

oneof:

message Animal {
   
string name = 1;
    oneof animal_type
{
       
Bird bird = 2;
       
Dog dog = 3;
   
}
}
message
Bird {
   
bool can_fly = 1;
}
message
Dog {
   
string breed = 1;
}

mixin common fields:

message Animal {
 
string name = 1;
}

message
Bird {
   
Animal animal = 1;
   
bool can_fly = 2;
}

message
Dog {
   
Animal animal = 1;
   
string breed = 2;
}

Using oneof makes it easier to define a generic collection of Animals, though all the subtypes need to be defined by the author of Animal.
Using the mixin strategy makes it easier for any "subclass" to extend the base type.

I'm trying to understand all the tradeoffs and am curious if people have developed best practices on this. Are there other considerations?

jeff

Feng Xiao

unread,
Oct 19, 2017, 2:18:21 PM10/19/17
to Jeff White, Protocol Buffers
I think the oneof approach is more common and more useful. Protobuf wire format doesn't carry message type info so if you use the second mixin pattern and send a Bird or Dog over the wire to another client, the other client can't really tell whether it's a Bird or Dog. Instead if you are sending a oneof, the other client can distinguish the difference by inspecting the oneof field.

If you don't want to define all types in the base Animal type, you can use the Any message instead:
message Animal {
  string name = 1;
  google.protobuf.Any any = 2;
}

Then if the other client knows about Bird, it can check whether the type is actually bird:

Animal animal = ...;
Bird bird;
if (animal.any().UnpackTo(&bird)) {
  // This is a bird.
  ...
}

jeff

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+unsubscribe@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages