google / google/protobuf.dart

Add getOrCreateX methods to make nested field mutates more ergonomic

Open
#96 2 comments 0 reactions 0 assignees View on GitHub
feature request
Dominant language
Dart
Stars
572
Forks
196
Avg merge
1h 59m
Merged PRs (30d)
2

Description

Consider the protos below:

```
message Outer {
optional Nested nested = 1;
...
}

message Nested {
optional int32 foo = 1;
optional int32 bar = 2;
optional AnotherMessage another_message = 3;
}
```

Given a reference to an instance of `Outer`, I want to mutate the value of an inner field. Ideally I'd write:

```
void populateBar(Outer outer) {
outer.nested.bar = 1;
}
```

This works if `outer.nested` is already populated. Otherwise `outer.nested` returns a default (read only) instance, and the set fails with an `UsupportedError`. To do this safely w/o knowledge of whether the field is populated you have to do something like this (which gets even more cumbersome for deeper nesting):

```
void populateBar(Outer outer) {
final nested = outer.has_nested ? outer.nested : new Nested();
if (!outer.has_nested) outer.nested = nested;
nested.bar = 1;
}
```

One way to make this easier would be to add another getter that, rather than returning a default instance, creates the field if it doesn't exist. Assuming the prefix `getOrCreate` we could do this:

```
void populateBar(Outer outer) {
outer.getOrCreateNested.bar = 1;

// And this works well for more deeply nested fields:
outer.getOrCreateNested.getOrCreateAnotherMessage.baz = 2;
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.