Skip to content

Simplify mapping iterables in toData and fromData implementations of common domain model classes #12

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
navibyte opened this issue Aug 10, 2021 · 2 comments
Labels
enhancement New feature or request 🗒️ attributes Related to the code package "attributes"

Comments

@navibyte
Copy link
Collaborator

See sample domain model classes with JSON serialization

On this sample PersonCollection is defined as:

class PersonCollection {
  final Iterable<Person> persons;

  const PersonCollection({required this.persons});

  factory PersonCollection.fromData(DataArray data) => PersonCollection(
        persons: data.objects
            .map((element) => Person.fromData(element))
            .toList(growable: false),
      );

  DataArray toData() => DataArray.of(
        persons.map((person) => person.toData()).toList(growable: false),
      );
}

Mapping iterables in both directions in fromData and toData could be easier to implement?

Find choices and add support on DataObject and/or DataArray.

@navibyte navibyte added 🗒️ attributes Related to the code package "attributes" enhancement New feature or request labels Aug 10, 2021
@navispatial
Copy link
Member

DataArray with new static constructor:

  static DataArray from<T extends Object>(
          Iterable<T> source, Object Function(T) convert) =>
      DataArrayView._protected(
          source.map<Object>(convert).toList(growable: false));

And DataElement with new method (implemented by DataArray and DataArrayView etc.)

  /// Returns a list of [T] mapped from child data arrays using [map] function.
  ///
  /// An optional [limit] when provided limits the number of returned objects.
  ///
  /// The returned list is immutable.
  ///
  /// Other child objects (that cannot be represented as a data array) are
  /// omitted from an iterable.
  List<T> arraysToList<T extends Object>(T Function(DataArray array) map,
      {int? limit});
}

This allows simplification of our sample to:

class PersonCollection {
  final Iterable<Person> persons;

  const PersonCollection({required this.persons});

  static PersonCollection fromData(DataArray data) =>
      PersonCollection(persons: data.objectsToList(Person.fromData));

  DataArray toData() =>
      DataArray.from<Person>(persons, (person) => person.toData());
}

Also other similar changes and improvements...

@navispatial
Copy link
Member

Implemented in Release version 0.8.0

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
enhancement New feature or request 🗒️ attributes Related to the code package "attributes"
Projects
None yet
Development

No branches or pull requests

1 participant