DEV Community

Discussion on: On the subtleties of OOP

Collapse
 
martinhaeusler profile image
Martin Häusler • Edited

First of all, thanks for the elaborate comment!

I totally agree that universal equality is difficult (if not impossible) to truly achieve. In my opinion, the Java designers did the best they could without totally going overboard with it. It is a huge improvement over what other languages do, Javascript for example has no real notion of equality other than reference equality (plus, interestingly, specific equalities for built-in types such as strings). But that is another matter entirely.

I think that, strictly speaking, a mathematician would disagree with the statement that a triple "is" a pair. However, a triple can be projected to a pair.

The best solution in this case is the one you outlined. Have Pair and Triple as independent classes (no inheritance) and let Triple have a method asPair that projects the triple to its first two entries, producing a new Pair. Also, Pair could have a toTriple(C third) method. This is also the mathematically correct way of doing it. Doing an "implicit projection" of the triple to the first two entries is questionable practice at best and dangerous at worst (as my example above has shown).

Oh, and Object#equals(...) is only getting started here. Things can get really hairy really quickly if we also add JDK Dynamic Proxies into the mix. The example I presented is really just the tip of the iceberg. My intention was to highlight how important it is to read the JavaDoc before implementing a method, and to focus on actual semantics rather than mere syntax.