views:

80

answers:

2

How do I make defensive copies of a Mutable Object which contains a mutable field in an Immutable Object?

class ImmutableObject {

  private final MutableObject immutable_field;

  ImmutableObject(MutableObject y) {
    this.immutable_field = y;
  }
}

class MutableObject {

  public int mutable_field;
}
  • The MutableObject does not have a constructor that lets me set the field.
  • The MutableObject's current state should be captured in the Immutable Object and never changed.
+3  A: 

What you need to do is in

  MutableObject return_immutable_field() {
    return immutable_field;
  }

Change to:

  MutableObject return_immutable_field() {
    MutableObject tmp = new MutableObject();
    tmp.mutable_field = immutable_field.mutable_field;
    return tmp;
  }

For an explanation see http://www.javapractices.com/topic/TopicAction.do?Id=15

Romain Hippeau
The problem is not while returning but while constructing.
kunjaan
@OP: In any case, it's basically the same.
trinithis
+2  A: 

Well, assuming that there is nothing to be done about the declaration of the mutable object class, one could leverage reflection (Class.newIntance() and Class.getFields()) to create a new object and copy field values. You could also implement deep copying in this manner. If the class supports serialization, then another hackish approach would be to serialize the object and then save a deserialized copy. If it is possible to fix the design of the mutable object, though, that would be a better approach.

Edit
For the particular example that you've given, Romain's answer does what you want. If you have a general mutable object that doesn't provide a mechanism for copying it and for which the type may not be known until later, then the reflection approach is how one would implement a copy mechanism.

Michael Aaron Safyan
Thanks, that covers the other part of the question. +1
Romain Hippeau