Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
import java.util.Date;

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;	
  }
}

This code also violates OBJ37-J. Do not return references to private data

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.

...