views:

61

answers:

1

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?

+2  A: 

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) { ... }
DS