objectbox-dart icon indicating copy to clipboard operation
objectbox-dart copied to clipboard

Immutable entities via copyWithId setter

Open rafuck opened this issue 3 years ago • 9 comments

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;
}

rafuck avatar Mar 04 '22 15:03 rafuck

Thanks, we'll have a look!

greenrobot-team avatar Mar 07 '22 07:03 greenrobot-team

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

greenrobot-team avatar Mar 07 '22 07:03 greenrobot-team

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.

rafuck avatar Mar 07 '22 20:03 rafuck

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.

greenrobot-team avatar Mar 15 '22 09:03 greenrobot-team

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 avatar Mar 15 '22 10:03 rafuck

Ping?

rafuck avatar Jun 16 '22 12:06 rafuck

@rafuck Haven't looked at this, yet.

greenrobot-team avatar Jun 20 '22 06:06 greenrobot-team

up

erdzan12 avatar Sep 22 '22 18:09 erdzan12

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

gombal88 avatar Aug 18 '23 14:08 gombal88