-
Notifications
You must be signed in to change notification settings - Fork 207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Value classes #2331
Comments
This sound very much like #1474. |
Right, it sounds like you're looking for a way to treat an existing representation (for example, certain objects of type In that case you might be able to use an upcoming Dart feature known as views: closed view PositiveInt on int {
factory PositiveInt(int value) {
if (value <= 0) throw ArgumentError('PositiveInt not positive');
return value;
}
factory PositiveInt.parsed(String value) => PositiveInt(int.parse(value));
PositiveInt operator +(PositiveInt other) => this + other;
}
void main() {
final result = addPositives(PositiveInt(3), PositiveInt.parsed('4'));
}
PositiveInt addPositives(PositiveInt a, PositiveInt b) => a + b; There are several things to note here:
I changed The client code looks like So all member accesses on a view type are resolved statically, but they can of course call methods on the underlying object (an instance of the 'on-type', here: |
@eernstg Ah! I had read that proposal but it makes much more sens now 😋 Goddamn the upcoming features are exciting. Can't wait. Shipping patterns, static meta programming and view in the same release would be a bomb of a release. Dart 3 kind of thing. |
Scala has value classes which can help statically type properties, also known as solving "primitive obsession".
Here is a nice article on them to understand why they can be useful and how they work. The gist of it is that they solve this not being caught as well as self validation, without having to use a real class wrapper:
They also do not suffer from performance issues enumerated here dart-lang/sdk#3888 but the "why" is outside the scope of my knowledge.
Validation
It's important for those Value classes to be able to self validate to protect invariants, protecting against those domain rules that prevents values existing in an invalid state
Transformation
I'm not sure that is in the article above but there can also be a need to be able to transform inputs. Eg: formatting an email value class to be lower case, etc.
Proposed Syntax
The text was updated successfully, but these errors were encountered: