freezed
freezed copied to clipboard
feat request: add `difference` method on freezed classes to determine the difference
Is your feature request related to a problem? Please describe.
When comparing two objects of the same type, I would like to be able to determine the "difference" between the two objects.
Describe the solution you'd like
Given the following freezed class:
@freezed
class Person with _$Person {
const factory Person({
required String name,
required int age,
}) = _Person;
}
I would like to find the difference between two instances:
final young = Person(
name: 'Dash',
age: 1,
);
final old = Person(
name: 'Dash',
age: 100,
);
// new method to be generated
final difference = old.difference(young);
// the "difference" object can be anything, just would prefer a simple API
assert(difference == [FreezedDifference<int>('age', 100, 1)]);
Example of a single difference class
/// used to describe the difference of one field between to identical objects
class FreezedDifference<T> {
const FreezedDifference(this.fieldName, this.thisValue, this.otherValue);
final String fieldName;
final T thisValue, otherValue;
}
Describe alternatives you've considered
Add all properties into a list by hand and then adding a difference method which iterates over the values. You can see my example implementation on this open equatable
issue.
Additional context Add any other context or screenshots about the feature request here.
What is the purpose of this feature exactly? I'm not sure why this would be useful
It would be mostly utility. The usefulness would be in evaluating changes/differences in objects/data uniformly. For example: having something like an audit log with tracking what change was made to a data.
What about making your object serializable, then comparing the json outputs? There are a few diff algorithm available for JSON already
Ideally, it could eliminate the the need for the encoding step (to/from Json or Map) and ensure only difference
can be used between two objects of the same type (Person
for the above example).
Also, I just now realized the #754 issue. It seems that this issue is similar that one.
Certainly, but the cost of adding a new feature is pretty high. Considering there's an existing solution, I would need a very good reason to natively include this inside Freezed
Completely understood. Would the feature be open to future PRs?
Not for now. It's unclear to me why this has to be made by Freezed.
But I encourage anyone who wants something similar to make a detailed explanation about why this is necessary
Considering there's a good-enough workaround, I don't plan on implementing this for now.