3 ms·
The Java impl for protobuf will never generate a NullPointerException, as calling `get` on a field would just return the default instance of that field. This w
by ynniv 2y ago
The Java impl for protobuf will never generate a NullPointerException, as calling `get` on a field would just return the default instance of that field.
This was a mistake. You still want to check whether it was initialized most of the time, and when you do the wrong thing it's even more difficult to see the error.
- kyrra 2y agoDepends on your use. If you are parsing a message you just received, I agree that you want to do a "has" check before accessing a field. But when constructing a message, having to manually create all the options is really annoying. (I do love the java builder pattern for protos). But I do know the footgun of calling "get" on a Java Proto Builder without setting it, as that actually initializes the field to empty, and could call it to be emitted as such. Such are the tradeoffs. I'd prefer null-safety to accidental field setting (or thinking a field was set, when it really wasn't).
- tantalor 2y ago> you want to do a "has" check before accessing a field You should only do that if the semantics of the not-set field are different than the default value, which should be rare and documented on the field.
- ynniv 2y agoI too enjoy defining my default attribute values at the protocol level, so they can never, ever be changed, and then defensively coding library functions in case the arguments are not constructed under the same semantic assumptions as I had years ago. Also everything needs to be marked optional or you'll need to restart the whole service mesh to change the schema.
- kyrra 2y agoDefault values in proto are considered an anti pattern and was removed from the language in proto3. Agreed that protocol level required is bad, and it's with proto3 made optional the default. Our team enforces required fields via proto annotations, which can be much more flexible (we have transitional states to be able to upgrade or downgrade the check)
- deleted 2y ago[deleted]
- rad_gruchalski 2y ago> Depends on your use. Okay, but look… If I wanted that, I’d create a wrapper library for it and call it a day. But not by default, please.