You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

Mutable classes are those which when instantiated, provide a reference such that the contents of the class can be altered anytime. It is important to provide means for creating copies of mutable class instances as it allows safe passing in and returning of class objects when they are used within method arguments.

Non-Compliant Code Example

In this non-compliant example, mutableClass uses a mutable Date object. If the caller changes the instance of the Date object (like incrementing the month), the class implementation no longer remains consistent with its old state. Both, the constructor as well as the getDate method are susceptible to abuse. This also defies attempts to implement thread safety.

public final class mutableClass {
  private Date d;
	
  public mutableClass(Date d) {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
      //check permissions
    }
    this.d = d;
  }
	
  public Date getDate() {
    return this.d;	
  }
}

Compliant Solution

Always provide mechanisms to create copies of the instances of a mutable class. This compliant solution implements the Cloneable interface and overrides the clone method to create a deep copy of both the object and the mutable Date object. Since using clone() independently only produces a shallow copy and still leaves the class mutable, it is advised to also copy all the referenced mutable objects that are passed in or returned from any method.

public final class cloneClass implements Cloneable {
  private Date d;
	
  public cloneClass(Date d) {
    SecurityManager sm = System.getSecurityManager();
      if (sm != null) {
	//check permissions
      }
      this.d = new Date(d.getTime());  //copy-in 
  }

  public Object clone() throws CloneNotSupportedException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
      //check permissions
    }
    final cloneClass cloned = (cloneClass)super.clone();
    cloned.d = new Date( d.getTime() );  //copy mutable Date object
    return cloned;
  }
	
  public Date getDate() {
    return new Date(this.d.getTime()); //copy and return
  }
}

At times, a class is labeled final with no accessible copy methods. Callers can then obtain an instance of the class, create a new instance with the original state and subsequently proceed to use it. Similarly, mutable objects obtained must also be copied when necessary.

References

Sun Secure Coding Guidelines
object.clone() http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#clone()

  • No labels