不支持可为 null 的 Setter/Getter
我们收到的反馈是,一些人希望 protobuf 能在他们选择的支持 null 的语言(特别是 Kotlin、C# 和 Rust)中支持可为 null 的 getter/setter。虽然对于使用这些语言的人来说,这似乎是一个有用的功能,但这一设计选择需要权衡取舍,这也导致 Protobuf 团队选择不去实现它。
显式存在 (explicit presence) 这一概念与传统的可为 null (nullability) 概念并不直接对应。这很微妙,但显式存在的设计哲学更接近于“字段不可为 null,但你可以检测字段是否被显式赋值。如果未赋值,正常访问会得到某个默认值,但你可以在需要时检查该字段是否被主动写入过”。
不设置可为 null 字段的最大原因是为了实现 .proto
文件中指定的默认值的预期行为。按照设计,对一个未设置的字段调用 getter 将返回该字段的默认值。
注意: C# 确实将消息字段视为可为 null。这种与其他语言的不一致性源于其缺少不可变消息,这使得创建共享的不可变默认实例成为不可能。因为消息字段不能有默认值,所以这种处理在功能上没有问题。
例如,考虑这个 .proto
文件
message Msg { Child child = 1; }
message Child { Grandchild grandchild = 1; }
message Grandchild { 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)
如果存在一个可为 null 的 getter,它必然会忽略用户指定的默认值(转而返回 null),这将导致令人意外和不一致的行为。如果可为 null getter 的用户想要访问字段的默认值,他们必须编写自己的自定义处理逻辑,以便在返回 null 时使用默认值,这反而消除了使用 null getter 本应带来的代码更简洁/简单的优势。
同样,我们不提供可为 null 的 setter,因为其行为会不直观。执行 set 操作后再执行 get 操作,返回的值可能并不总是相同;并且调用 set 操作有时会影响字段的 has-bit,有时则不会。
请注意,消息类型的字段始终是显式存在字段(带有 hazzer)。Proto3 默认标量字段为隐式存在(不带 hazzer),除非它们被明确标记为 optional
,而 Proto2 不支持隐式存在。在 Editions 中,除非使用了隐式存在特性,否则显式存在是默认行为。我们预期未来几乎所有字段都将具有显式存在性,因此与可为 null getter 相关的便利性问题,预计会比 Proto3 用户之前遇到的更加突出。
由于这些问题,可为 null 的 setter/getter 将从根本上改变默认值的使用方式。虽然我们理解其潜在的效用,但我们认为它所带来的不一致性和困难使其得不偿失。