© Conrad Weisert, Information Disciplines, Inc., June 1 2009
NOTE: This document may be circulated or quoted from freely, as long as the copyright credit is included..
Rules and contracts | This article expands a brief point in a book review that has elicited strong dissent. |
The Java community keeps reminding class designers of things they have to do to honor various conventions. One of them is:
"Always override - various sources including Joshua Bloch:
Effective Java |
They warn us that if we fail to do so we will have violated or broken a "contract". That sounds dire. We certainly don't want to be accused of breaking solemn contracts.
But after a moment's reflection, we wonder what the purpose of that contract is. What kinds of things might we want to compare for equality? What kinds of things might we want to retrieve by value from a table? Are those two categories of things the same?
Hash tables are used to retrieve items by the value of some key field. Key fields typically include:
We rarely if ever use the values of numeric data items as key fields. We'd be surprised to find a program trying to retrieve from a hash table:
|
Clearly, it would be bizarre (and probably unreliable) to use Money objects,
Temperature objects, or TimeOfDay objects as keys for retrieval.
Therefore, there is very little reason
to implement the It's not just numeric classes that shouldn't implement
Even if we can't conceive of using some object as a key field to a hash table,
we may still want to compare it with another object. Therefore, we may well want
to implement a Boolean |
Solving the ProblemAnother approach that may tempt us is to declare Alas, that "solution" won't work! The obstacle lies with the
Liskov substitution principle combined with a poor choice by Java's designers. The
universal root class We shall propose a more disciplined solution in a later article. |
Return to IDI home page
Last modified September 28, 2009