'Strong types in Protocol Buffers
Since protobuf has no support for type alias is it a valid approach to create a strong type using a message with a single value member like the following?
message ID {
uint32 value = 1;
}
message Entity {
ID id = 1;
uint32 count = 2;
}
Or is it better to use just the scalar:
message Entity {
uint32 id = 1;
uint32 count = 2;
}
The strong type makes in my opinion the code more readable and has the benefit that in the case I want to change the id from uint32 to uint64 I would only have to change one line. Since I haven't seen this online, I wondered if there is any drawback.
Solution 1:[1]
There is some minor drawback for the developer, in that they have to refer to entity.id.value instead of just entity.id. Whether or not the strong type ends up paying off or causes more problems than it solves will, I think, come down to the individual circumstances of the project.
However, it is worth exploring where the strong type approach might go. For example, consider a message field that is supposed to be a bearing, valid between 0 and 359. If you had a Bearing type, then you've got some consistency of how bearing values are implemented in the application source code. You can then more readily check (through code review) that everywhere Bearing is used, it is also checked for validity. The code review is helped because you can simply search for all variables declared Bearing, and check what is done with them.
Whereas without the strong type approach, bearing values might be called all manner of things such as bearing, brng, angle, heading, etc, and it then takes more than a simple search to track down all places where bearing values are being used.
This though exposes one of the big weaknesses of Google Protocol Buffers, in that there is no way to define validity constraints in the schema other than in a comment and review source code to see that the comment has been actioned in the application source code. Whereas, something like ASN.1 schema (which aren't so very different at a basic level to GPB schema) does allow formal expression of validity constraints, and the generated code will automatically enforce them for you at serialisation / deserialisation. This is a big time saver.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bazza |
