How should I add methods a Protobuf message?
Suppose I have in my .proto file:
package proto;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
and I want to add a method, say, string concatenateNameEmail()
to the message.
What I do right now is I create my own C++ class like this:
class Person : public proto::Person
{
public:
Person( proto::Person const & person_ )
: proto::Person(person_)
{}
string concateNateNameEmail()
{
...
}
};
So the downside is I need to call proto::Person copy constructor. Is there a more elegant solution than this?
The proto-backwards-compatibility plugin is a Maven plugin to run a backwards compatibility check on a set of protobuf IDL files. The plugin can be integrated into various phases of a maven build to check that any changes to a set of . proto files are backwards compatible.
It's possible to import proto3 message types and use them in your proto2 messages, and vice versa. However, proto2 enums cannot be used in proto3 syntax.
We have seen production issues caused by this multiple times and it's pretty much banned everywhere inside Google for anyone to add/remove required fields. For this reason we completely removed required fields in proto3. After the removal of "required", "optional" is just redundant so we removed "optional" as well.
Protobuf has a hard limit of 2GB, because many implementations use 32-bit signed arithmetic. For security reasons, many implementations (especially the Google-provided ones) impose a size limit of 64MB by default, although you can increase this limit manually if you need to.
Google Protobufs are specifically not intended to be extended. Here's a paragraph from the documentation (in the middle of this: http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html):
Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they don't make good first class citizens in an object model. If you want to add richer behaviour to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. ... You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.
I can see how such advice would seem annoying if you only wanted that one method, but in general it's pretty good advice. If you really have no other functionality to warrant creating an application-specific "Person" class, there is nothing wrong with just defining a top-level function:
string concatenateNameEmail(const proto::Person &person) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With