Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Why Bother?

Was it necessary to write a test for hashCode? Did we even need to change it from a hard-coded 1 return value? Both questions are good, and there’s no "right" answer for either.

I personally am compelled to write a test for any real logic that I code. I’ll try to think hard about a way to write a test for something, even if the test ends up being a little hokey. I’d rather have the confidence level that the test gives me.

The bigger question is whether we need to bother with the hashCode algorithm at all. I can find myself on both sides of this debate. For a 52-card deck, a hard-coded return value means that we essentially end up with a list of 52 cards. That in turn means that all operations must iterate through 52 elements. Performance-wise, this isn’t a big deal for the kinds of things we would be doing with decks. At least, not yet. Impact is negligible. I could view providing a better hashCode algorithm as a waste of development and maintenance time. It’s something we can easily add later.

But it is wasteful, and will disturb a lot of sensibilities, including mine. A dumb hashCode algorithm effectively boils a high-performing set or hash-based map (e.g., HashMap) into a list construct. It goes against the kinds of things that most of us were taught about software development. At times, I’m willing to disturb these classic sensibilities. Maybe it’s time to let go of this one. Who can convince me one way or another?

Next segment: "Shuffling and Dealing." Meanwhile, here’s the code (source.zip) we’ve built in this installment.

  • + Share This
  • 🔖 Save To Your Account