Should Equality be commutative within a Class Hierachy?
- by vossad01
It is easy to define the Equals operation in ways that are not commutative. When providing equality against other types, there are obviously situations (in most languages) were equality not being commutative is unavoidable. However, within one's own inheritance hierarchy where the root base class defines an equality member, a programmer has more control.
Thus you can create situations where
(A = B) ? (B = A), where A and B both derive from base class T
Substituting the = with the appropriate variation for a given language. (.Equals(_), ==, etc.)
That seems wrong to me, however, I recognize I may be biased by background in Mathematics. I have not been in programming long enough to know what is standard/accepted/preferred practice when programming.
Do most programmers just accept .Equals(_)may not be commutative and code defensibly. Do they expect commutativity and get annoyed if it is not. In short, when working in a class hierarchy, should effort me made to ensure Equality is commutative?