On Wed, Oct 18, 2017 at 3:04 PM, Jeff White <[email protected]> wrote:

> 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?
>
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 [email protected].
> To post to this group, send email to [email protected].
> Visit this group at https://groups.google.com/group/protobuf.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Reply via email to