Types for Deep/Shallow Cloning
K.W.E. Cheng · 2012
In Java, exact copies of objects are achieved by calling clone methods. By default, these clone methods create a shallow clone; if programmers desire sheep cloning (in between shallow and deep cloning) then they must override and maintain custom implementations of clone methods. For the programmer, this is tedious and error prone. The cloning approach proposed in a recent paper, Trust the Clones [15], addresses this problem by using object ownership as the copy/clone policy and deriving the implementation of clone methods from them. In this report, we extend this cloning approach to deal with cloning when there are arrays, subclassing and generics. We explore the problems specific to each feature and propose solutions that allow clone methods to be derived from ownership types. As a proof of concept, I implemented the basic cloning approach as a Java language extension using Polyglot (an extensible compiler framework). This compiles classes written in the extended Java language into standard Java with generated clone method implementation. I also discovered situations where this cloning approach has problems – type errors sometimes occur when cloning without owners-as-dominators. We describe and formulate solutions to statically prevent these problematic cases from occurring.