Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (vkp) v1.0

...

Wiki Markup
Note that the {{clone()}} method must manually clone the {{Date}} object. This step is usually unnecessary when the object contains only primitive fields or fields that refer to immutable objects. When the fields contain data such as unique identifiers or object creation times, the new values of the fields must be calculated and assigned manually in the {{clone()}} method \[[Bloch 2008|AA. Java References#BlochBibliography#Bloch 08]\].

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. The clone() method should copy all internal mutable state as necessary. In this compliant solution, the Date object is copied.

...

Wiki Markup
Callers can use the {{clone()}} method to obtain an instance of such a mutable class. The {{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. Finally, the {{clone()}} method must create and return a new instance of the enclosing class ({{MutableClass}}) using the newly created member instance ({{d}}) \[[SCG 2007|AA. Java References#SCGBibliography#SCG 07]\]. 

Compliant Solution (Copy Constructor)

...

Wiki Markup
\[[API 2006|AA. Java References#APIBibliography#API 06]\] [method clone()|http://java.sun.com/javase/6/docs/api/java/lang/Object.html#clone()]
\[[Security 2006|AA. Java References#SecurityBibliography#Security 06]\]
\[[SCG 2007|AA. Java References#SCGBibliography#SCG 07]\] Guideline 2-2 Support copy functionality for a mutable class
\[[SCG 2009|AA. Java References#SCGBibliography#SCG 09]\] Guideline 2-3 Support copy functionality for a mutable class
\[[Bloch 2008|AA. Java References#BlochBibliography#Bloch 08]\] Item 39: Make defensive copies when needed and Item 11: Override clone judiciously
\[[MITRE 2009|AA. Java References#MITREBibliography#MITRE 09]\] [CWE ID 374|http://cwe.mitre.org/data/definitions/374.html] "Mutable Objects Passed by Reference", [CWE ID 375|http://cwe.mitre.org/data/definitions/375.html] "Passing Mutable Objects to an Untrusted Method"

...