Immutability offers several benefits, such as thread-safety , and prevention against of inadvertent modification of fields , and malicious tampering. Class invariants and state of immutable objects are always consistent with their requirements, so defensive copying while accepting input or returning values is unnecessary. However, it is sometimes impossible to make sensitive classes immutable. Fortunately, there is a mechanism exists that allows code to expose mutable classes to untrusted code by granting read-only access. This is largely achieved , which is achieved largely through unmodifiable wrappers. For example, the Collection
classes include a set of wrappers that allow clients to observe an unmodifiable view of a Collection
object.
...
This noncompliant code example consists of class Mutable
, which allows the internal array object to be modified. :
Code Block | ||||
---|---|---|---|---|
| ||||
class Mutable { private int[] array = new int[10]; public int[] getArray() { return array; } public void setArray(int[] i) { array = i; } } // ... private Mutable mutable = new Mutable(); public Mutable getMutable() {return mutable;} |
...
This compliant solution constructs a MutableProtector
object by extending the Mutable
class. :
Code Block | ||||
---|---|---|---|---|
| ||||
class MutableProtector extends Mutable { @Override public int[] getArray() { return super.getArray().clone(); } @Override public void setArray(int[] i) { throw new UnsupportedOperationException(); } } // ... private Mutable mutable = new MutableProtector(); public Mutable getMutable() {return mutable;} // May be safely invoked by untrusted caller having read ability |
The MutableProtector
wrapper class overrides the getArray()
method , and clones the array. Although calling code gets a copy of the mutable object's array, the original array remains unchanged and inaccessible. The setArray()
method is also overridden to throw an exception if the caller attempts to use this method on the returned object. This object can be passed to untrusted code when read-access to the data is permissible.
...
Failure to provide an unmodifiable, safe view of a sensitive mutable object to untrusted code can lead to malicious tampering and corruption of the object.
...