Nelz's Blog

Mah blogginess

[BACKPOST] Shades of Equals()

So, I got into a couple of pretty interesting conversations about object identity the other day. Yeah, I know what Hibernate says about establishing identity, but I think there is a larger question at hand.

We use so many different frameworks, and some of these frameworks make assumptions (or demands) about what the equals() method does. When you are dealing with several frameworks, each context may be slightly different.

So, what if we could pass to the frameworks what to use as a comparator rather than the equals() method?

Here’s an example: What if we decide we want to use the db surrogate key as our "business identity" (even though Gavin et. al. strongly caution against it…) Then, the only time this would create a problem for us is before the newly created object is persisted in the db. During this window, what if we try to hold several of these created objects in a Collection? Since they all have null id’s, they would all be equal, and we’d end up with only 1 object in the Collection. What if we said to the Collection that during this window in the lifecycle of these objects, we use the similarTo() method instead? (This would be a lot easier to do compile-time checking with the "generics" features in Java 1.5…) This would enable us to use something other than the id, like possibly the ~firstName and ~lastName of a User object, within the context of this Collection. Wouldn’t that be helpful?

I admit, I haven’t thought this suggestion out to it’s completion yet… And, I’m sure there are plenty of thesises (thesesses?) on the subject, but I thought I’d post a little sumthin’ sumthin’ about where I was going with this idea…