Protobuf and optional values

Just small note to all you guys if you are using google protobuf library for communicating with server.

Lets say you have simple protobuf message with one optional numeric field:

message query {
  required string request = 1;
  optional int64 limit = 2
}

If you are using some dynamic language in your server backend, you can end up having code like this:

// msg contains Parsed Query protobuf message
String query = msg.getQuery();
Long limit = msg.getLimit();

Now question, what value of limit variable will be, if message will not have limit field set? Answer is: 0. Not null.

This is happening because actual return value for getLimit() is primitive long, not object. I assume google guys did that for performance reasons.

You can easily solve it using ?: operator:

Long limit = msg.hasLimit() ? msg.getLimit() : null;

Summary: working with protobuf, always remember that it is using primitives for numeric types and you have to use has methods to avoid getting zeros instead of nulls.