Should Equality be commutative within a Class Hierachy?
Posted
by
vossad01
on Programmers
See other posts from Programmers
or by vossad01
Published on 2012-10-05T17:15:12Z
Indexed on
2012/10/05
21:53 UTC
Read the original article
Hit count: 164
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?
© Programmers or respective owner