Tuesday, November 29, 2011

Java clone method - why to avoid





No programming language in this world is perfect and Java is no exception to it. There are quite a few bad design decisions that were made earlier and because of backward compatibility reason continue to exist even today.




One such bad design decision is related to clone method. At a first glance, it might seem like a good idea to use a method named clone to copy an object. But as we will see bellow, this is not really the case with Java’s Object.clone method.




Java has an interface called Cloneable. In principle, one should implement this interface if it is desired to make an object cloneable. The problem here is that this interface doesn’t define any methods. Instead, a clone method is defined in the Object class. The mess that it creates is implementing an interface changes the behavior of a method defined 'elsewhere'.




Moreover Object.clone is a protected method, so one must override it with a public method in order for it to be accessible – or else it should be called reflectively, but then it would get too complicated.




This is a bad design mainly because an interface should enforce you to implement some behavior in your class. Without implementing the proper method, your code shouldn’t even compile. But what Cloneable interface does is to say (in the javadoc documentation) that you should override Object.clone. Also, for the clonning to happen correctly, you would need to have your 'whole' class hierarchy 'overriding' clone. This means all super classes and all mutable objects referenced from all those classes. What about 3rd party class that doesn’t do so?





The simple way out is to consider the following two options instead of using clone method.
1. Use a copy constructor:
e.g. public MyClass(MyClass myClass) {
// initialize your fields here
}
OR
2. Create some utility method for copying the object:
public static MyClass newInstanceMyClass myClass) {
// create your object and return it here
}
The 'Effective Java' book has dealt with the topic in a more detailed way. Please refer to it for further study.