Skip to content

copyWith, hashCode and operator==. - #976

Closed
pro100andrey wants to merge 23 commits into
serverpod:mainfrom
pro100andrey:copy_with
Closed

pro100andrey wants to merge 23 commits into
serverpod:mainfrom
pro100andrey:copy_with

Conversation

@pro100andrey

@pro100andrey pro100andrey commented May 30, 2023 •

Copy link
Copy Markdown
Contributor

Many state management solutions like Redux, BloC, and Riverpod utilize data validation and notification mechanisms based on the data structure. To ensure successful validation, models need to meet certain requirements, such as implementing methods like hashCode and operator==.

To support this, I have added the capability to generate these methods for models.

748

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Breaking changes

No breaking changes

Example:

class: Post

fields:
  userId: int
  created: DateTime
  relations: List<int>
  description: String
  likes: List<int>
  tags: List<String>
generated post.dart
/* AUTOMATICALLY GENERATED CODE DO NOT MODIFY */
/*   To generate run: "serverpod generate"    */

// ignore_for_file: library_private_types_in_public_api
// ignore_for_file: public_member_api_docs
// ignore_for_file: implementation_imports

// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:serverpod_client/serverpod_client.dart' as _i1;
import 'package:collection/collection.dart' as _i2;

class Post extends _i1.SerializableEntity {
  Post({
    required this.userId,
    required this.created,
    required this.relations,
    required this.description,
    required this.likes,
    required this.tags,
  });

  factory Post.fromJson(
    Map<String, dynamic> jsonSerialization,
    _i1.SerializationManager serializationManager,
  ) {
    return Post(
      userId:
          serializationManager.deserialize<int>(jsonSerialization['userId']),
      created: serializationManager
          .deserialize<DateTime>(jsonSerialization['created']),
      relations: serializationManager
          .deserialize<List<int>>(jsonSerialization['relations']),
      description: serializationManager
          .deserialize<String>(jsonSerialization['description']),
      likes: serializationManager
          .deserialize<List<int>>(jsonSerialization['likes']),
      tags: serializationManager
          .deserialize<List<String>>(jsonSerialization['tags']),
    );
  }

  int userId;

  DateTime created;

  List<int> relations;

  String description;

  List<int> likes;

  List<String> tags;

  @override
  Map<String, dynamic> toJson() {
    return {
      'userId': userId,
      'created': created,
      'relations': relations,
      'description': description,
      'likes': likes,
      'tags': tags,
    };
  }

  @override
  bool operator ==(dynamic other) {
    return identical(this, other) ||
        (other is Post &&
            (identical(other.userId, userId) || other.userId == userId) &&
            (identical(other.created, created) || other.created == created) &&
            (identical(other.description, description) ||
                other.description == description) &&
            const _i2.DeepCollectionEquality().equals(
              relations,
              other.relations,
            ) &&
            const _i2.DeepCollectionEquality().equals(
              likes,
              other.likes,
            ) &&
            const _i2.DeepCollectionEquality().equals(
              tags,
              other.tags,
            ));
  }

  @override
  int get hashCode => Object.hash(
        userId,
        created,
        description,
        const _i2.DeepCollectionEquality().hash(relations),
        const _i2.DeepCollectionEquality().hash(likes),
        const _i2.DeepCollectionEquality().hash(tags),
      );

  Post copyWith({
    int? userId,
    DateTime? created,
    List<int>? relations,
    String? description,
    List<int>? likes,
    List<String>? tags,
  }) {
    return Post(
      userId: userId ?? this.userId,
      created: created ?? this.created,
      relations: relations ?? this.relations,
      description: description ?? this.description,
      likes: likes ?? this.likes,
      tags: tags ?? this.tags,
    );
  }
}

Currently, the generation of these methods only occurs for the client-side when the user invokes serverpod generate.

Perhaps, you would like me to add the generation of these methods with other way. Here are some approximate examples:

with yaml:

class: Post
extra: server,client
fields:
  userId: int
  created: DateTime
  relations: List<int>
  description: String
  likes: List<int>
  tags: List<String>

with serverpod generate:

serverpod generate --extra-data-class <server, client, both>

@pro100andrey pro100andrey changed the title Copy with copyWith, hashCode and operator==. May 30, 2023
@vlidholt

vlidholt commented Jun 1, 2023

Copy link
Copy Markdown
Collaborator

This looks great! :)

The tests are likely failing because you haven't run util/generate_all, which runs serverpod generate on all the packages in Serverpod.

@vlidholt
vlidholt requested a review from Isakdl June 1, 2023 11:22
@pro100andrey

pro100andrey commented Jun 1, 2023 •

Copy link
Copy Markdown
Contributor Author

@vlidholt in progress

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice PR, I love this feature, thank you! 😄 ❤️

Only one thing I would like you to change and that is the test and group descriptions. They don't tell us much about what is going on in the tests currently.

General guidelines:

  • The test description should be precise enough that I understand what we are testing, think of them as documentation for the production code.
  • The test description should make it very obvious what went wrong if the test fails when running them. I.E. when I see 20-30 test results and one random test failed I should get an idea of what happened without looking at the test implementation.
  • Each test should test only one specific behavior (this also makes it easier to write the description).

I put an example of some test descriptions in the test file!

@pro100andrey

Copy link
Copy Markdown
Contributor Author

hi @Isakdl, could you check current tests implementation, please?

@pro100andrey pro100andrey left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check

@pro100andrey

pro100andrey commented Jun 1, 2023 •

Copy link
Copy Markdown
Contributor Author

@vlidholt , @Isakdl,

I wanted to provide a summary of changes I have made recently regarding the extra generation feature for models.

To enable the generation of extra methods for the model, it is necessary to add the "extra" flag. Here is an example of the code implementation:

class: ExtraDataClass
...
extra: client
fields:
  duration: Duration
...

Currently, only client-side support is available, as implementing server-side support would require significant modifications. However, I have made provisions to enable future expansions in this regard.

For the implementation of the operator== and hashCode methods, I followed a similar approach to what was done in the "freezed" package.

Regarding the standard copyWith method, I decided not to use it because it does not support setting null values. Instead, I have devised an alternative solution to address this limitation.

To provide more context, please refer to the following link for a detailed explanation of the problem and the approach I took to overcome it.

If you have any questions or require further clarification on these developments, please don't hesitate to reach me. I am more than happy to provide any additional information you may need.

@pro100andrey
pro100andrey requested a review from Isakdl June 1, 2023 16:55
@pro100andrey

Copy link
Copy Markdown
Contributor Author

@vlidholt , @Isakdl What do you think about the field extra: client in yaml files? Or is it better to use extraMethods: client?

@vlidholt

vlidholt commented Jun 2, 2023

Copy link
Copy Markdown
Collaborator

@pro100andrey, I think that the @==, copyWith, and hashCode should be added to all generated classes. They need to work both client-side and server-side, and there should be tests for both. I don't think there is a reason to add the extra: attribute, it just complicates things.

Need to dig into what you did with setting null values in copyWith, but generally I think Freezed may be a good template as that's what developers are typically familiar with.

@pro100andrey

pro100andrey commented Jun 2, 2023 •

Copy link
Copy Markdown
Contributor Author

Hi @vlidholt, ok, but I understand that users may have specific use cases that could potentially be affected if we generate both server and client models by default.

I propose introducing the option for users to have control over whether they want the generation of extra methods. This way, they can decide if they need these additional methods based on their individual requirements.

Like this:

class: ExtraDataClass
...
extraMethods: true
fields:
  duration: Duration
...

Think about it.

If you insist, I will enable default generation for both server and client.

Thanks!

@braj065

braj065 commented Jun 3, 2023

Copy link
Copy Markdown

Should be optional for both server and client. And leave room for when dart dataclasses land.

* main:
  feat: Adds migrate --repair command to CLI. (#980)
  fix: Correctly validates tag names for database migrations. (#970)
  feat: Database migrations are applied by priority. (#968)
  fix: Handle invalid return types when parsing endpoint methods. (#967)
  test: Fixes issues in migration and adds tests. (#966)

# Conflicts:
#	packages/serverpod/lib/src/generated/database/database_definition.dart
#	packages/serverpod/lib/src/generated/database/database_migration.dart
#	packages/serverpod_service_client/lib/src/protocol/database/database_definition.dart
#	packages/serverpod_service_client/lib/src/protocol/database/database_migration.dart
#	tools/serverpod_cli/lib/src/generator/generator_database_definition.dart
#	tools/serverpod_cli/lib/src/migrations/generator.dart
@pro100andrey

pro100andrey commented Jun 5, 2023 •

Copy link
Copy Markdown
Contributor Author

Hi @vlidholt.

After adding default support for copyWith, @==, and hashCode for the Server and Client classes, there are breaking changes:

To adhere to the immutability principles, the fields should be final. Therefore, the setColumn method, which was used only to set the id value, has been removed. Now, this can be done through copyWith. As a result, the insert method has been modified, and it now returns a TableRow with set the id.

Future<int?> storeObjectWithObject(
    Session session,
    ObjectWithObject object,
  ) async {
   // insert returns ObjectWithObject instance with set id
    var result = await ObjectWithObject.insert(session, object);

    return result.id;
  }

Positive aspects:

  • All data classes support the const constructor.
  • All class fields are immutable.

Please review the recent changes and let me know if I'm moving in the right direction.

Thanks!

@vlidholt

vlidholt commented Jun 7, 2023 •

Copy link
Copy Markdown
Collaborator

@pro100andrey We cannot approve any breaking changes for this PR. Adding immutability has the potential to break a lot of things for our users. Also, most of the tests doesn't pass at the moment, these all need to work for the PR to be approved. A tip is that you can run the tests on your own fork on Github by pushing to the main or dev branch (you may also need to turn on the actions on your Github repository).

To get this PR approved either:

  1. Remove the immutability requirement.
  2. Make it opt in using the syntax below.
class: MyClass
immutable: true
fields:
  myInt: int
  myString: String

If I remember correctly, the setColumn method is used by the database layer. So there may be some larger changes required there if it is removed.

@pro100andrey

Copy link
Copy Markdown
Contributor Author

@vlidholt Ok, but what's the point of including copyWith for server-side if the fields in it are mutable?

@pro100andrey

Copy link
Copy Markdown
Contributor Author

@vlidholt I can provide you with code generation for the client side only that adheres to the best practices of immutability. Let's start with that.

@vlidholt

vlidholt commented Jun 7, 2023

Copy link
Copy Markdown
Collaborator

@pro100andrey I would assume there can be cases where it makes sense so copy over modifying an object. Having the extra method will add very little overhead, so I don't see a problem in including it even for mutable classes.

It may be a better idea to break this PR up into two parts to get it approved faster:

  1. Add the comparisons and copyWith methods.
  2. Add option for immutability.

@pro100andrey

Copy link
Copy Markdown
Contributor Author

@vlidholt I will work on it as soon as I have a little time, hopefully today :)

@vlidholt

Copy link
Copy Markdown
Collaborator

Closing this as it is stale, but added a link in the issue so that we can revisit ahead of our next release.

@vlidholt vlidholt closed this Jul 12, 2023
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 12, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants