google/protobuf.dart

Why aren't not null checks included in the generated code?

Pingear opened this issue · 1 comments

Hello!
I cannot track the entire history of the debate over the presence or absence of required fields in the Protocol Buffers format, but in my opinion, it is illogical to replace fields with default values. If you believe that all fields should be required, then I should not have the ability to create an class without initializing any fields, as the current situation leads to errors. For example, here is a perfectly valid code snippet:

@override
  Future<TokensDto> register(ServiceCall call, RegisterRequest request) async {
	return TokensDto();
  }

while TokensDto has 3 requierd fields

syntax="proto3";

service AuthRpc {
    rpc Register(RegisterRequest) returns (TokensDto);
}

message TokensDto {
    string access_token = 1;
    string refresh_token = 2;
    bool is_true = 3;
}

and response of course

{
    "access_token": "",
    "refresh_token": "",
    "is_true": false
}

So, it seems that in order to use the format, we have to generate an infinite number of checks. If that's the case, then why aren't these checks included in the generated code?

I suppose that the library developers are experienced individuals who have already considered everything. Perhaps it's just me being new and not having read the documentation thoroughly. Could you please point me to where the benefits of this situation are described for someone like me, an average developer creating new products using Protocol Buffers and gRPC and Dart?

osa1 commented

I cannot track the entire history of the debate over the presence or absence of required fields

proto3 does not have required fields, all fields are optional. This is per proto3 design and not an implementation decision.

Note: when I say "all fields are optional" I don't mean "all fields are marked as optional", I just mean they're literally optional, i.e. parsing should succeed if a field is missing.

it is illogical to replace fields with default values

This is per protobuf design, not an implementation choice. Without the optional keyword you cannot distinguish a missing field from a field with the default value. New proto3 spec page explains this nicely: https://protobuf.dev/programming-guides/proto3/#field-labels.

If you believe that all fields should be required, then I should not have the ability to create an class without initializing any fields

As mentioned, proto3 does not have required fields.

Closing as this is working as intended.

I recommend reading the proto3 spec before using this library. It's possible that the design is not right for you and you may want to consider another format.