plato icon indicating copy to clipboard operation
plato copied to clipboard

ISet<T> constraint wanted

Open mlhaufe opened this issue 3 years ago • 5 comments

ISet<T> implies that T must implement Equality.

mlhaufe avatar Mar 09 '22 19:03 mlhaufe

If we use an Equality function in the set implementation, then it no longer needs to be implemented by T. So in this case it would eliminate the need for the constraint on T directly in the interface. Do you agree?

cdiggins avatar Mar 11 '22 14:03 cdiggins

Extrinsic equality is possible on Value Objects as you can just compare the properties. Example: two 3D points.

For Entity Objects this is also possible if the key is observable. Example: two Customer objects are considered the same if they have the same ID. It doesn't matter if the address changes, it's still the same Customer.

In both cases we are relying on exposed properties to determine the result: Observably Equal.

We have to deal with objects though that have hidden state. This is one of the reasons why Equality is generally determined by the object itself.

Another reason is that if you leave it to the container to determine the equality of the elements you would not be able to do this generically and would end up with a switch statements or a maze of if-elsedom to find the right behavior. Alternatively you might end up with a number of subclasses to solve this problem: Set, IntSet, StringSet. Or you end up holding on to an equality lambda and pass that into the constructor at runtime for each container:

new Set<Point3>(Point3Equals) new List<Point3>(Point3Equals) etc.

Whereas if the object owned and had the responsibility for defining equality you avoid this repetition and I suspect have less code to deal with.

mlhaufe avatar Mar 12 '22 17:03 mlhaufe

I think the same argument applies to Ordering/Sortability

mlhaufe avatar Mar 12 '22 19:03 mlhaufe

Whereas if the object owned and had the responsibility for defining equality you avoid this repetition and I suspect have less code to deal with.

Very good point.

cdiggins avatar Mar 13 '22 17:03 cdiggins

I think the same argument applies to Ordering/Sortability

Sorting by varying criteria is common enough that keeping the comparer lambda/interface in the collection could be worthwhile, but I think I need to experiment with using it more to see whether the trade-off is worth it.

Thanks for the thoughtful comments and discussion.

cdiggins avatar Mar 13 '22 17:03 cdiggins