不支持可空 Setter/Getter
我们收到反馈,一些人希望 Protobuf 在他们选择的支持 null 的语言中(尤其是 Kotlin、C# 和 Rust)支持可空的 getter/setter。虽然这对于使用这些语言的人来说似乎是一个有用的特性,但这个设计选择存在权衡,Protobuf 团队因此选择不实现它们。
不支持可空字段的最大原因是 .proto 文件中指定的默认值的预期行为。按照设计,对未设置的字段调用 getter 会返回该字段的默认值。
注意:C# 确实将消息字段视为可空。这种与其他语言的不一致源于缺乏不可变的消息,这使得创建共享的不可变默认实例成为不可能。由于消息字段不能有默认值,这并没有功能上的问题。
例如,考虑这个 .proto 文件
message Msg { optional Child child = 1; }
message Child { optional Grandchild grandchild = 1; }
message Grandchild { optional int32 foo = 1 [default = 72]; }
以及相应的 Kotlin getter
// With our API where getters are always non-nullable:
msg.child.grandchild.foo == 72
// With nullable submessages the ?. operator fails to get the default value:
msg?.child?.grandchild?.foo == null
// Or verbosely duplicating the default value at the usage site:
(msg?.child?.grandchild?.foo ?: 72)
以及相应的 Rust getter
// With our API:
msg.child().grandchild().foo() // == 72
// Where every getter is an Option<T>, verbose and no default observed
msg.child().map(|c| c.grandchild()).map(|gc| gc.foo()) // == Option::None
// For the rare situations where code may want to observe both the presence and
// value of a field, the _opt() accessor which returns a custom Optional type
// can also be used here (the Optional type is similar to Option except can also
// be aware of the default value):
msg.child().grandchild().foo_opt() // Optional::Unset(72)
如果存在可空 getter,它必然会忽略用户指定的默认值(转而返回 null),这会导致令人惊讶和不一致的行为。如果可空 getter 的用户想要访问字段的默认值,他们将不得不编写自己的自定义处理代码,以便在返回 null 时使用默认值,这消除了使用 null getter supposedly 带来的更清晰/更简单的代码的好处。
类似地,我们不提供可空 setter,因为其行为会令人费解。执行 set 然后 get 不会总是返回相同的值,并且调用 set 只会在某些时候影响字段的 has-bit。
请注意,消息类型字段始终是显式存在字段(带有 hazzers)。Proto3 中,标量字段默认是隐式存在(没有 hazzers),除非它们被显式标记为 optional
,而 Proto2 不支持隐式存在。在 Editions 中,显式存在是默认行为,除非使用了隐式存在特性。随着几乎所有字段都将具有显式存在的未来预期,与可空 getter 相关的人机工程学问题预计将比 Proto3 用户更值得关注。
由于这些问题,可空 setter/getter 将彻底改变默认值的使用方式。虽然我们理解其潜在的实用性,但我们认为它引入的不一致性和困难性不值得。