Generating immutable types
- Dominant language
- Dart
- Stars
- 572
- Forks
- 196
- Avg merge
- 1h 59m
- Merged PRs (30d)
- 2
Description
Protobuf is a great tool for many applications. One of such applications is developing cross-platform [value objects](https://martinfowler.com/bliki/ValueObject.html) with a common source of truth for the structure. This way a Java/C#/\ can use the _same_ types as a Dart/JS/mobile-native client.
Unlike code generated for e.g. Java, Dart Protobuf classes are always mutable from the API standpoint. Although an individual message can be frozen, its interface will always hint towards mutability. This breaks the elegance of the value object pattern alongside having a number of technical disadvantages:
- async changes of a mutable state are easy to control on the high level, e.g. a message is **reset**, but hard to control on the low level, e.g. a field of a field of a message has changed;
- mutable messages traditionally have problems with `==` and `hashCode`, as their output may change when the message changes, which may break some data structures, such as `HashMap`s (this is also discussed in this [issue](https://github.com/dart-lang/protobuf/issues/34));
- having to check if a message is frozen or not is an additional mental load for a code author.
My questions are:
1. Is it possible that generating truly immutable classes will be added at some point in the future?
2. Are there any downsides to immutable types in Dart of which I am not aware? Is this an already well-thought-through decision that is just not obvious to me?
If adding immutable types is to be considered, let me suggest that the [`built_value`](https://github.com/google/built_value.dart) library may provide some insight into how that would look. They have some excellent and mature API for an immutable value object.
Contributor guide
Assessment
This issue has not been assessed yet.