3 ms·
At my place of work, we typically follow the "message type" solution in situations like this. I don't think it's the most legible solution, but it's the best we
by gen220 7y ago
At my place of work, we typically follow the "message type" solution in situations like this. I don't think it's the most legible solution, but it's the best we can do with the proto spec: I always feel like I should qualify these fields with a comment explaining the apparently pointless wrapper.
Google themselves provide https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/wrappers.proto https://github.com/protocolbuffers/protobuf/blob/master/src/... to deal with this situation.
Quoted from the documentation:
> Wrappers for primitive (non-message) types.
> These types are useful for places where we need to distinguish between the absence of a primitive typed field and its default value.
It should probably be advertised more, as we've experienced that default values of optional fields are a surprising feature for smart developers who are new to protobufs. Maybe it's seen as a wart in the design? Getting rid of Null is hard.
I kinda wish they went with the approach that all fields are required, unless they are explicitly declared as optional. This is how Rust does it, and people seem to like it.
- m0zg 7y agoI think you got it backwards. The current situation where unset field results in a value is the equivalent of "null", it's the opposite of "getting rid of null". The previous design didn't have that problem.
- gen220 7y agoI might be misunderstanding you, but the current situation results in a “zero” value, whereas “Null” would represent “unspecified”, or the absence of a value. I wouldn’t say that the current spec supports null, unless you’re using a wrapper like the one linked. It’s the distinction between an optional type and an optional value (default value). With optional values but no optional types, you can’t be certain about the caller’s intentions. It’s a distinction that’s subtle but important, therefore a “gotcha”. Getting rid of null is a noble idea, because of the headaches that null tends to induce. Optional types (like Rust’s) is a neat way to get the behavior of null without the value of null. Proto3 doesn’t have null, it’s replaced with arcane wrapping that’s arguably less straightforward. Please let me know if I’m talking past you, it isn’t intentional, just late in the day. :)