Versions Compared

Key

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

Mutable classes are those which when instantiated, return a reference such that the contents of the instance (instance members) can be altered. It is important to provide means for creating copies of mutable classes to allow passing their respective class objects to untrusted code. The defensive copying ensures that untrusted code cannot manipulate the object's state. The copying mechanism can be advertised by overriding java.lang.Object's clone() method. However, providing a clone() method by itself, does not obviate the need to create defensive copies when receiving input from untrusted code and returning values to the same (see FIO31-J. Defensively copy mutable inputs and mutable internal components and OBJ37-J. Defensively copy private mutable class members before returning their references). Only a trusted caller can be expected to responsibly call the overriding clone() method before passing instances to untrusted code.

...

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 the object. If it is possible that the untrusted code can call accessor methods can be called from untrusted code, it is also advisable to copy all the mutable objects that are passed in before they are stored in the class (FIO31-J. Defensively copy mutable inputs and mutable internal components) or returned from any methods (OBJ37-J. Defensively copy private mutable class members before returning their references). This is because untrusted code cannot be expected to call the object's clone() method to operate on the copy. This compliant solution provides a clone() method to trusted code and also guarantees that the state of the object cannot be compromised when the accessor method is called directly from untrusted code.

...

Wiki Markup
At times, a mutable class's memberinstance class field is declared {{final}} with no accessible copy methods. Callers can use the {{clone()}} method to obtain an instance of the mutable class. This {{clone()}} method must create a new instance of the {{final}} member class and copy the original state to it. The new instance is necessary because no accessible copy method may be available in the member class. If the member class evolves in the future, it is critical to include the new state in the manual copy. \[[SCG 07|AA. Java References#SCG 07]\] 

As far as possible, a mutable class that defines a clone() method, must be declared final. This ensures that untrusted code cannot subclass and override the clone() method to supply a spurious instance. Also refer to FIO31-J. Defensively copy mutable inputs and mutable internal components.

Exceptions

EX1: Sensitive classes should not be made cloneable. (MSC37-J. Make sensitive classes noncloneable)

...