objectbox / objectbox-dart

Flutter database for super-fast Dart object persistence
https://docs.objectbox.io/getting-started
Apache License 2.0
927 stars 115 forks source link

Immutable entities via copyWithId setter #393

Open rafuck opened 2 years ago

rafuck commented 2 years ago

Immutable entities support (see Issue-307)

@Entity()
class TestEntityImmutable {
  @Id(useCopyWith: true)
  final int? id;

  final int payload;

  TestEntityImmutable copyWith({int? id, int? payload}) =>
      TestEntityImmutable(
        id: id,
        payload: payload ?? this.payload,
      );

  const TestEntityImmutable({this.id, required this.payload});

  TestEntityImmutable copyWithId(int newId) =>
      (id != newId) ? copyWith(id: newId) : this;
}
greenrobot-team commented 2 years ago

Thanks, we'll have a look!

greenrobot-team commented 2 years ago

From a quick look this breaks the contract that put modifies the same object as mentioned in the original issue.

rafuck commented 2 years ago

From a quick look this breaks the contract that put modifies the same object as mentioned in the original issue.

Yes, put and putMany (and etc) change ID for objects before (or after) send it to storage. In the case of immutability (in this PR) it is imposible to change immutable objects, and it sends to storage new objects, constructed by copyWith. But it is obvious for the client code that an immutable entity should not change. And if such code uses immutability, it should not rely on side effects. In other cases, everything works as before.

Maybe it might make sense to define new methods for immutable entities (putImmutable, putManyImmutable, etc)... It is not problem.

greenrobot-team commented 2 years ago

Again thanks for this! I guess you already figured out that relations are going to be a problem as well.

We'll have a look at this in more detail and if it makes sense to integrate.

rafuck commented 2 years ago

Again thanks for this! I guess you already figured out that relations are going to be a problem as well.

Yes. My bad: I don't think about relations at the start.. It is really lot of work to make relations in immutable case!

We'll have a look at this in more detail and if it makes sense to integrate.

Thank you

rafuck commented 1 year ago

Ping?

greenrobot-team commented 1 year ago

@rafuck Haven't looked at this, yet.

erdzan12 commented 1 year ago

up

gombal88 commented 9 months ago

any update in the case of immutable classes and autoincrementing id?