Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define equality as identity for reference types?

I'm often tempted to make my reference types Equatable by defining == as ===. This allows me, to cite one example of many, to replace the verbose:

collection.contains(where: { $0 === object })

with:

collection.contains(object)

but I have a nagging feeling that I'm doing something Wrong™. What are the downsides to defining equality to be identity? Is this a common pattern?

like image 659
andyvn22 Avatar asked May 26 '26 08:05

andyvn22


1 Answers

Defining equality as identity is useful only in situations when two different representations of an object are impossible. Otherwise you would end up with objects that look identical, but fail when compared for equality.

This is OK when you keep a cache of objects, ensuring that identical entities are represented with a single objects.

If the rule "one entity-one object" is broken, your objects become useless in all situations when equality is used, such as hash sets, hash maps, and linear searches.

like image 156
Sergey Kalinichenko Avatar answered May 27 '26 22:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!