I have been struggling in how to explain this in an interesting way. The whole reason why we need data and value classes pertains to how Dart actually works.
First, unlike Haskell being pure functional, Dart is a procedural language THAT INCLUDES functional programming. Its what they are calling a mixed language.
Since we want our Data-Model objects to freely move between both Object Oriented Programming and Functional Programming they need to be immutable.
That then gives these benefits:
1. They can easily be used OOP-wise and FP-wise
as functional requires immutable and we get more
beneifts under OOP when using immutable
2. Since immutable means final fields, final is similar
to conts in that we do get improved compiler
performance.
3. final fields and thus immutable classes are thread safe.
So now lets deal with why we need two classes, a Data class and a Value Class. That has to do with what the equality operator does in that it compares objects. As objects in two different memory locations always have different hashCodes.
Thus for a non collection to get a value equality we change the equality operator to comparing fields. The hashCode is typically changed to compute the runtime type has raised the power of the fields hash.
Due to Dart not having an equality operator for collections; we instead have to set up the immutable classs so that we get that value equality for collections.
For collections to be value equality we want the individual entries in the collection to be key and value equal and the hashCode to be computed with both the key and value of each entry in the collection.
So, now let me cover the Data Class with the twist of pairing it with data fixtures to make storyboard prototyping and testing easier.
Keep reading with a 7-day free trial
Subscribe to Fred’s Flutter Newsletter to keep reading this post and get 7 days of free access to the full post archives.