0

I've got a .proto file with a few messages which looks something like this,

Message messageA{
  required double value =1;
  //more fields
} 

Message messageB{
   required int32 value =1;
   //more fields
} 

I'd like to verify that each message added to the file will have a "value" field. If it doesn't, the proper result will be a failing unit test.

Is there a better way to do this without hoping the next programmer will add messages instances to a test?

Thanks.

1 Answers1

1

You could achieve this with protocol buffer reflection. The FileDescriptor class allows you to iterate through all messages in the file (use the "message_type(int index)" function for that). You can then use "FindFieldByName()" on the message Descriptor to determine if there is a field named "value".

On a completely unrelated side-note, I would strongly encourage you to use "optional" instead of "required" in your protocol buffer messages. The application requirements are best imposed by the application, itself, rather than within the deserialization logic; using "optional" allows application code to more gracefully fail if this condition is not met, whereas "required" imposes a crash, and unfortunately changing a field in a message from "required" to "optional" later can be very dangerous (because old applications may still consider it required, while subsequent applications may no longer populate it).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • Thanks Michael. Found it already :-) . Works great. I'm using protobuf for enforcing a contract with an external software, hence required can be quite useful here. – Yuval Carmel Aug 05 '14 at 14:36
  • @YuvalCarmel, even for external software, it's better to indicate it in a comment and apply your own validation rather than using Parse() to enforce this validation, because 1.) you may eventually have a case where you allow an alternative combination of fields to supplant the previous field 2.) not all implementations enforce this checking (e.g. Python's implementation of protobuf is equivalent to ParsePartial where it doesn't check for required fields). – Michael Aaron Safyan Aug 05 '14 at 22:26