If objects are immutable it’s very easy and efficient to make a deep copy of object – just copy memory pointer of that object.
It’s also very easy and efficient to do deep equality check – just compare the pointers.
But what happens if data comes from the outer world and we need to check its identity?
Consider following example:
- Application query data for a Post from DataBase, deserialize it into the immutable Post Object (Model) and cache it in memory.
- After a some time Application query the same data again, and also deserialize it into the immutable Post Object.
- Now, how we can check if Post has been changed? We can’t just compare references of immutable objects to check identity. References will be different (because we deserialized the data twice) but the data itself still may be the same.
How to handle such situations?
Two approaches that may be workable, or may give you more ideas for future approaches:
Approach #1 is probably a good one if a suitable dictionary type is available, but approach #2 could have some considerable advantages as well. The biggest annoyance with #2 is that it adds an extra layer of indirection to object accesses. Still, being able to have objects consolidate themselves quickly into cliques could be a major plus.