The Artima Developer Community
Sponsored Link

Legacy Design Forum
Canonical Object Idiom

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Oh Oh

Posted by Bill Venners on January 24, 2000 at 8:31 PM

> > The code for equals() in the article ensures that the Object passed as an argument is of the same type
> > as itself by trying a typecast; failure results in a ClassCastException which is caught
> ...
> >
> > I saw this simpler code elsewhere:
> > if (obj != null && (obj instanceof this.getClass()))
> ...
> > Is this OK? Or are there any hidden glitches in this that aren't apparent to me?
>
Aha! I said to myself. A hidden glitch in your seemingly more
straightforward and more efficient approach is that the
if statement will be true if the class of the comparison is
a subclass of the class on which equals() is invoked. But then
I got to wondering about the approach in the article, and sure
enough the same is true. I think that's a bug in both of these
approaches.

> Yes, it's OK, but it could still be even shorter. It's OK to use a null reference with
> the instanceof operator, it'll just return false. Also, there's little need for the
> method call to get the current class's class, since you're in that file anyway.

> Hence:

> public boolean equals(Object o) {
> if( !( o instanceof Worker )) {
> return false;
> }
> Worker w = (Worker) o;
> return (name.equals(w.name) && doList.equals(w.doList));
> }

I think the class of both objects must be the same, which
none of these approaches are checking for. I'll post again
with a way to do that. And, I'll change the idiom to match.
Any ideas yourself?

bv





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us