Skip to content

Value classes #2331

Closed
Closed
@cedvdb

Description

@cedvdb

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:

class Product {
  final String id;
  final String name;
}

abstract class ProductRepository {
  Product find(String id);
  Product findByName(String name);
}

// somewhere
final productName = 'x';
productRepository.find(productName);

They also do not suffer from performance issues enumerated here dart-lang/sdk#3888 but the "why" is outside the scope of my knowledge.

Because of Flutter, we care increasingly about compilation to native code. Part of that means having efficient support for unboxed value types. Being able to implement the primitive number types would interfere with that, so we don't intend to go in that direction.

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

class PositiveInt(int _value) {
   // validation
   PositiveInt(this._value) : assert(_value >= 0);
   // transformation
   PositiveInt.parsed(String value): this(int.parse(value));
}

void main() {
  final result = add(PositiveInt(3), PositiveInt.parsed('4'));
}

int add(int a, int b) => a + b;

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions