The Artima Developer Community
Sponsored Link

Java Design Issues
A Conversation with Ken Arnold, Part VI
by Bill Venners
October 14, 2002

<<  Page 3 of 5  >>

Advertisement

The clone Dilemma

Bill Venners: In The Java Programming Language, you discuss clone and suggest how to use it. You have said to me previously that you think clone is broken.

Ken Arnold: I think clone is a real mess.

Bill Venners: But given clone's current state, how would you recommend people use it? What do you think of Bloch's suggestion in Effective Java to create copy constructors rather than using the clone approach?

Ken Arnold: The problem with a copy constructor is that you have to know the type of thing you're cloning or copying. You have to make a Foo given an old Foo that is passed into the copy constructor. But if the object the client holds is not a Foo, but is a Foo subtype, then you could end up doing type truncation, which you don't want to do.

Bill Venners: What do you mean by type truncation?

Ken Arnold: Suppose you have a Foo, which has a subclass Bar. If you ask Foo to clone itself and you have a Bar object, Foo will do all the Bar stuff. But if you use this copy constructor mechanism and you tell Foo to create a new Foo and pass in the old Bar, you will get a new Foo instead of a Bar. You lose the bottom of the type.

Bill Venners: You're fubar.

Ken Arnold: You're definitely fubar. So using a copy constructor implies a mechanism where you ask the passed object its type. You get its class object, and invoke its copy constructor by reflection. When you do that, you are way into ugliness.

If I were to be God at this point, and many people are probably glad I am not, I would say deprecate Cloneable and have a Copyable, because Cloneable has problems. Besides the fact that it's misspelled, Cloneable doesn't contain the clone method. That means you can't test if something is an instance of Cloneable, cast it to Cloneable, and invoke clone. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.

<<  Page 3 of 5  >>


Sponsored Links



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