Wednesday, September 28, 2011

PMD - Clone Rules

This is the twenty second installment of explanation of PMD rules covering Cloning of objects.

Clone Implementation Rules

The Clone Implementation ruleset contains a collection of rules that find questionable usages of the clone() method.
Clone is a method used to create a copy of objects in Java. The resulting object must be an exact replica of the object from which it was cloned. It is important to note that in the process of cloning if we use a statement like
this.attribute = classcloned.attribute
will only achieve a shallow copy as only the reference of the object attribute will be copied into the cloned class. Any changes to attribute in the clone will impact the original object. Instead we should use
this.attribute = classcloned.attribute,clone()
This will ensure that the cloned object gets a cloned copy of the attribute object too.

ProperCloneImplementation

Object clone() should be implemented with super.clone().

Example

class Foo{
    public Object clone(){
        return new Foo(); // This is bad
    }
}

CloneThrowsCloneNotSupportedException

The method clone() should throw a CloneNotSupportedException.

Example

public class MyClass implements Cloneable{
     public Object clone() { // will cause an error
          MyClass clone = (MyClass)super.clone();
          return clone;
     }
}

CloneMethodMustImplementCloneable

The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.

Example

public class MyClass {
public Object clone() throws CloneNotSupportedException {
  return foo;
}
}

No comments: