user15257608
user15257608

Reputation: 11

Modeling Interfaces in Protobuf

I'm new to Protobuf and understand that there isn't a way to model an interface implementation in Protobuf. We have an existing set of domain objects that implements a common "IBase" interface in C#.

One option is to use the protobuf generated class only as a DTO and convert it in to the domain class after deserialization but that would mean I will need to create a separate DTO class which I use in .proto and convert it to domain class after deserialization

I would like to model the DerivedProduct class in proto and generate the client and server classes in C# and Java respectively. Please advise on the best practice to model existing interface implementations like below. I have provided a simple representation below.

interface IBase  
{  
    string ProductName {get;set;}  
    void Add(string baseProduct);  
}

interface IDerived: IBase  
{                                 
    double ProductRate {get;set;}  
}

class DerivedProduct : IDerived      
{
    string ProductName {get;set;}  
    void Add(string baseProduct){ }  
    double ProductRate {get;set;}  
}

Upvotes: 1

Views: 1020

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502835

I don't know about the situation for Java, but in C# the classes generated by the protoc plugin are partial classes. So you'd model your proto as:

message DerivedProduct {
    string product_name = 1;
    double product_rate = 2;
}

Run protoc to generate the code, and then add another partial class manually:

public partial class DerivedProduct : IDerived
{
    // The properties will already be generated by protoc in another file

    public void Add(string baseProduct)
    {
        // Implementation here
    }
}

Upvotes: 4

Related Questions